最近有一个场景是Child2组件点击让Child1组件里面的state的值发生改变,Child1是一个公用组件,把里面的state值改为props传递,修改内容太多,容易出错,就想找其他的方法来解决兄弟组件调用方法问题,下面看代码:
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组件触发一个事件的时候,就可以直接这样调用this.child1.onChange(),Child1组件里面就会直接调用onChange函数,修改text为Child1 onChange;
到这里就可以实现调用兄弟组件,其实还是用父组件做了中间传递。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月20日
2024年09月20日
- 王菲.2006《菲常好听》引进版[低速原抓WAV+CUE]
- 《三日危情独家的记忆》女角色介绍
- 《天国拯救》拉泰比武大会攻略
- 任天堂推出《马里奥惊奇》NS捆绑包 10月24日发售
- 《孤岛惊魂》能否逆转育碧颓势?曝系列新作正招兵买马
- 天命人呼叫战术轰炸!玩家自制《黑神话:悟空》轰炸机Mod
- 群星.1992-滚石九大天王·十二出好戏【滚石】【WAV+CUE】
- 群星.1994-新滚石九大天王之年度大丫滚石】【WAV+CUE】
- 坣娜.1998-别恋【非常喜】【WAV+CUE】
- 《草原经典 最炫草原风 2CD》[WAV/分轨][980MB]
- 《不烧不选 经典国语极品珍藏》[WAV/分轨][500MB]
- 《绝对主打 流行原创金曲 2CD》[WAV分轨][1.1GB]
- 《赛博朋克2077》更新上线:支持AMD FSR3
- 《塞尔达传说:智慧的再现》提前半个月偷跑,引发玩家担忧
- 战锤40K星际战士2全职业介绍|全职业技能效果一览