假设我有以下反应代码。
<Navigation parentWindow={this} />
<p>Sub Pages</p>
<ReactCSSTransitionGroup
component="div"
transitionName="page-transition"
transitionEnterTimeout={0}
transitionLeaveTimeout={500}
>
{React.cloneElement(this.props.children, {
key: location.pathname
})}
</ReactCSSTransitionGroup>ReactCSSTransitionGroup最终将呈现一个由ContactPage.js创建的<ContactPage />。下面是ContactPage.js的样子:
import React from 'react';
export default class Page extends React.Component
{
testMe() {alert('Hello World!');}
render() {return <div>Hello</div>;}
}从由Navigation.js创建的Navigation.js中,我希望能够触发ContactPage.testMe()。所以我在我的Navigation.js里做了这个
import React from 'react';
export default class Page extends React.Component
{
render() {
this.props.parentWindow.props.children.testMe();
return <div>Navigate me</div>;
}
}但是,当我运行这个项目时,我的导航会给出一个错误:
Uncaught TypeError: this.props.parentWindow.props.children.testCall我该如何解决这个问题?
发布于 2016-11-04 21:51:14
理论上,您可以通过使用refs来实现这一点。在ParentWindow组件中,您将向克隆的子组件分配一个ref,然后将其作为导航的支柱传递。
React的工作方式与其他JS库略有不同,它迫使您将业务逻辑或事件逻辑移动到父组件,并将其作为支持传递下来。我建议您将回调函数传递给导航页面,当触发该回调函数时,它将调用ContactPage方法。
class Navigation extends React.Component {
render() {
this.props.onAlertParent();
return <div>Navigate me</div>;
}
}
class ParentWindow extends Component {
alertChild() {
if (this.childNode && this.childNode.testMe) {
this.childNode.testMe();
}
}
render() {
<div>
<Navigation onAlertParent={() => this.alertChild()} />
<p>Sub Pages</p>
<ReactCSSTransitionGroup
component="div"
transitionName="page-transition"
transitionEnterTimeout={0}
transitionLeaveTimeout={500}
>
{React.cloneElement(this.props.children, {
key: location.pathname,
ref: (node) => { this.childNode = node; }
})}
</ReactCSSTransitionGroup>
</div>
}
}注意Navigation组件是如何通过道具接收回调函数的,导航元素不需要知道任何关于其兄弟姐妹的信息,它使用父元素与它们通信。
的反应方式是通过传递数据或回调在组件之间使用道具进行通信。总是有一种比调用元素方法更好的通信方式。甚至我建议的方法都是缺陷的,因为它仍然在从元素中调用方法。
https://stackoverflow.com/questions/40429236
复制相似问题