栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

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

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

最近有一个场景是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 (
   {this.state.text}
  );
 }
}

是第二个子组件,和Child1是兄弟组件;

class Child2 extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
  };
 }

 render() {
  return (
   Child2
  );
 }
}

home 父组件

class Home extends React.Component {

 constructor(props) {
  super(props);
  this.state = {
  };
 }
 onRef=(ref)=>{
  this.child1=ref;
 }

 render() {
  return (
   
    
    {
      this.child1.onChange&&this.child1.onChange()
     }
    } />
    
  );
 }
}

分析

  • 第一步:在Child1组件的componentDidMount生命周期里面加上this.props.onRef(this),把Child1都传递给父组件,
  • 第二步父组件里面 this.onRef方法为onRef=(ref)=>{this.child1=ref;};
  • 第三步 Child2组件触发一个事件的时候,就可以直接这样调用this.child1.onChange(),Child1组件里面就会直接调用onChange函数,修改text为Child1 onChange;

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/78614.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号