你可以讓父組件作爲兩個組件的容器重新呈現。因此,所有狀態和函數都在父組件中處理,並將它們作爲道具傳遞給其他組件。
例如
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組件中的狀態。 –