您可以将父组件作为两个组件的容器。所以所有的状态和函数都在父组件中处理,并将它们作为props传递给其他组件。
例如
class Parent extends React.Component {
constructor() {
super();
this.state = {
controls: controls
}
}
onClick = (dataFromChild2) => {
//Resetting
this.setState({controls: dataFromChild2})
}
render() {
return (
<div>
<Child1 gridControl={this.state.controls}/>
<Child2 onClick={this.onClick}/>
</div>
)
}
}
您可以在子组件中访问gridControl
和onClick
fromthis.props
更新
这样想,您拥有具有处理数据所需的状态和功能的父组件。子组件获取这些数据并相应地更新它们的状态。
假设父组件是这样的:
class Parent extends React.Component {
constructor() {
super();
this.state = {
gridControl: {}
}
}
onChild2ButtonClick = (dataFromChild2) => {
this.setState({
gridControl: dataFromChild2
});
};
render() {
return (
<div>
<Child1 controls={this.state.gridControl}/>
<Child2 onClick={this.onChild2ButtonClick}/>
</div>
);
}
}
Child2 组件是这样的:
class Child2 extends React.Component {
constructor() {
super();
}
onClick = () => {
var data = {};
this.props.onClick(data);
};
render() {
return (
<div>
<button onClick={this.onClick}/>
</div>
);
}
如果您正在为 Child1 使用状态,并且不想将它们更改为具有 Parent 组件中的函数的 props 来处理它们,那么您可以componentWillReceiveProps
使用从父组件接收到的新 props更新方法中的状态,以便发送的props将匹配 Child1 组件中使用的状态。
希望这能解决问题。