网络编程 
首页 > 网络编程 > 浏览文章

react 兄弟组件如何调用对方的方法示例

(编辑:jimmy 日期: 2024/10/26 浏览:3 次 )

最近有一个场景是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;

到这里就可以实现调用兄弟组件,其实还是用父组件做了中间传递。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:React 路由懒加载的几种实现方案
下一篇:详解React 的几种条件渲染以及选择
一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 SiteMap