react 兄弟組件如何調(diào)用對方的方法示例
最近有一個場景是Child2組件點擊讓Child1組件里面的state的值發(fā)生改變,Child1是一個公用組件,把里面的state值改為props傳遞,修改內(nèi)容太多,容易出錯,就想找其他的方法來解決兄弟組件調(diào)用方法問題,下面看代碼:
Child1 是第一個子組件
class Child1 extends React.Component { constructor(props) { super(props); this.state = { text:'Child1' }; } onChange=()=>{ this.setState({ text:'Child1 onChange' }) } componentDidMount(){ this.props.onRef&&this.props.onRef(this) } render() { return ( <div>{this.state.text}</div> ); } }
是第二個子組件,和Child1是兄弟組件;
class Child2 extends React.Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div onClick={this.props.onClick}>Child2</div> ); } }
home 父組件
class Home extends React.Component { constructor(props) { super(props); this.state = { }; } onRef=(ref)=>{ this.child1=ref; } render() { return ( <div className="home"> <Child1 onRef={this.onRef}/> <Child2 onClick={ ()=>{ this.child1.onChange&&this.child1.onChange() } } /> </div> ); } }
分析
- 第一步:在Child1組件的componentDidMount生命周期里面加上this.props.onRef(this),把Child1都傳遞給父組件,
- 第二步父組件里面 <Child1 onRef={this.onRef}/> this.onRef方法為onRef=(ref)=>{this.child1=ref;};
- 第三步 Child2組件觸發(fā)一個事件的時候,就可以直接這樣調(diào)用this.child1.onChange(),Child1組件里面就會直接調(diào)用onChange函數(shù),修改text為Child1 onChange;
到這里就可以實現(xiàn)調(diào)用兄弟組件,其實還是用父組件做了中間傳遞。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于Webpack5 Module Federation的業(yè)務解耦實踐示例
這篇文章主要為大家介紹了基于Webpack5 Module Federation的業(yè)務解耦實踐示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12react最流行的生態(tài)替代antdpro搭建輕量級后臺管理
這篇文章主要為大家介紹了react最流行的生態(tài)替代antdpro搭建輕量級后臺管理示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08Taro?React自定義TabBar使用useContext解決底部選中異常
這篇文章主要為大家介紹了Taro?React底部自定義TabBar使用React?useContext解決底部選中異常(需要點兩次才能選中的問題)示例詳解,有需要的朋友可以借鑒參考下2023-08-08如何不使用eject修改create-react-app的配置
許多剛開始接觸create-react-app框架的同學,不免都會有個疑問:如何在不執(zhí)行eject操作的同時,修改create-react-app的配置。2021-04-04