互換的青春
2019-07-25 15:22:25
如何在React中更新父狀態(tài)?我的結(jié)構(gòu)如下:Component 1
- |- Component 2
- - |- Component 4
- - - |- Component 5 Component 3組件3應(yīng)該根據(jù)組件5的狀態(tài)顯示一些數(shù)據(jù)。由于props是不可變的,我不能簡單地將它保存在組件1中并轉(zhuǎn)發(fā)它,對(duì)吧?是的,我讀過有關(guān)redux的內(nèi)容,但不想使用它。我希望只有反應(yīng)就可以解決它。我錯(cuò)了嗎?
3 回答

波斯汪
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
對(duì)于子父通信,您應(yīng)該傳遞一個(gè)函數(shù),將狀態(tài)從父級(jí)設(shè)置為子級(jí),就像這樣
class Parent extends React.Component { constructor(props) { super(props) this.handler = this.handler.bind(this) } handler(someValue) { this.setState({ someVar: someValue }) } render() { return <Child handler = {this.handler} /> }}class Child extends React.Component { render() { return <Button onClick = {this.props.handler}/ > }}
這樣,孩子可以通過調(diào)用帶有props傳遞的函數(shù)來更新父級(jí)的狀態(tài)。
但是你必須重新考慮組件的結(jié)構(gòu),因?yàn)閾?jù)我所知,組件5和3不相關(guān)。
一種可能的解決方案是將它們包裝在更高級(jí)別的組件中,該組件將包含組件1和3的狀態(tài)。該組件將通過props設(shè)置較低級(jí)別的狀態(tài)。

catspeake
TA貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個(gè)贊
我發(fā)現(xiàn)以下工作解決方案將onClick函數(shù)參數(shù)從child傳遞給父組件:
傳遞方法的版本()
//ChildB componentclass ChildB extends React.Component { render() { var handleToUpdate = this.props.handleToUpdate; return (<div><button onClick={() => handleToUpdate('someVar')}> Push me </button> </div>) }}//ParentA componentclass ParentA extends React.Component { constructor(props) { super(props); var handleToUpdate = this.handleToUpdate.bind(this); var arg1 = ''; } handleToUpdate(someArg){ alert('We pass argument from Child to Parent: ' + someArg); this.setState({arg1:someArg}); } render() { var handleToUpdate = this.handleToUpdate; return (<div> <ChildB handleToUpdate = {handleToUpdate.bind(this)} /></div>) }}if(document.querySelector("#demo")){ ReactDOM.render( <ParentA />, document.querySelector("#demo") );}
傳遞箭頭功能的版本
//ChildB componentclass ChildB extends React.Component { render() { var handleToUpdate = this.props.handleToUpdate; return (<div> <button onClick={() => handleToUpdate('someVar')}> Push me </button> </div>) }}//ParentA componentclass ParentA extends React.Component { constructor(props) { super(props); } handleToUpdate = (someArg) => { alert('We pass argument from Child to Parent: ' + someArg); } render() { return (<div> <ChildB handleToUpdate = {this.handleToUpdate} /></div>) }}if(document.querySelector("#demo")){ ReactDOM.render( <ParentA />, document.querySelector("#demo") );}
添加回答
舉報(bào)
0/150
提交
取消