如果必须将状态从仪表板传递到侧边栏,则必须从仪表板的渲染功能渲染侧边栏。在这里,您可以将仪表板的状态传递给补充工具栏。
程式码片段
class Dashboard extends Component {...... render(){ return( <Sidebar data={this.state.data1}/> ); }}
如果您希望仪表板接收对传递到边栏的道具(data1)所做的更改,则需要提升状态。即,您必须将功能引用从仪表板传递到补充工具栏。在补充工具栏中,无论何时要将data1传递回仪表板,都必须调用它。代码段。
class Dashboard extends Component { constructor(props){ ... //following is not required if u are using => functions in ES6. this.onData1Changed = this.onData1Changed.bind(this); } ... ... onData1Changed(newData1){ this.setState({data1 : newData1}, ()=>{ console.log('Data 1 changed by Sidebar'); }) } render(){ return( <Sidebar data={this.state.data1} onData1Changed={this.onData1Changed}/> ); }}class Sidebar extends Component { ... //whenever data1 change needs to be sent to Dashboard //note: data1 is a variable available with the changed data this.props.onData1changed(data1);}
参考文档:https :
//facebook.github.io/react/docs/lifting-state-
up.html
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)