你可以让父组件作为两个组件的容器重新呈现。因此,所有状态和函数都在父组件中处理,并将它们作为道具传递给其他组件。
例如
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>
)
}
}
您可以从this.props
的gridControl
和onClick
在孩子部件
UPDATE
它认为这种方式,你有处理所需要的状态和功能父组件数据。儿童组件将这些数据进行相应的更新。
假设父组件是这样的:
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组件中的函数处理它们,然后使用从父组件收到的新道具更新componentWillReceiveProps
方法中的状态,以便发送的道具将与Child1组件中使用的状态相匹配。
希望这可以解决问题。
网格布局的状态在儿童1内完全控制。我没有看到我如何将它作为父母的道具传递,它在那里的许多功能中被操纵。我也不太确定我是否从您的示例中获取数据流。孩子2会将状态推回?你应该这样做吗? – cbll
如何将“datafromchild2”传递给父组件中的函数?在调用onClick时,您可以使用Child2组件中的 – cbll
发送数据。所以它会是这样的'this.props.onClick(data)'。 由于您没有使用商店系统。我认为这会做到这一点。您可以使用'componentWillReceiveProps'生命周期方法更新Child1组件中的状态。 –