父级调用子孙级,有时我们需要点击最外层的组件,然后触发子孙组件的某个事件

360 阅读1分钟

很多层组件嵌套,最外层的组件点击,为了触发某个孙组件的一个事件

1. 组外层要触发的closeHeaderDropDown事件

this.state = {
  isShowEventDeatil: false
}

// 传给子级用的方法(为了拿到子级的this)
 onRef = (ref) => {
    this.child = ref
 }
 
 // 触发子组件的事件
 closeHeaderDropDown = () => {
   // this.child上面已经拿到 
   this.child.childFn();
 }


render() {
	return (
          <div>
            <div onClick={this.closeHeaderDropDown}>
              <div className="close_detail">×xxxxxxxx</div>
            </div>
            // 要触发的组件BetDetail
           <BetDetail onRef={this.onRef}/>
          </div>
    )
}

2. BetDetail组件

componentDidMount() {
   //通过pros接收父组件传来的方法, 这样父组件可以拿到子组件的控制
   this.props.onRef(this)
}

// 传给子级用的方法(为了拿到子级的this)
onRef = (ref) => {
   this.child = ref
}

// 调用子级用的方法
childFn = (e) => {
   this.child.childFn();
}

render() {
   return  <BetDetailHeader onRef={this.onRef}>
}

3. BetDetailHeader 组件

componentDidMount() {
  //通过pros接收父组件传来的方法
  this.props.onRef(this)
}

// 传给子级用的方法(为了拿到子级的this)
onRef = (ref) => {
   this.child = ref
}

// 调用子级用的方法
childFn = (e) => {
   this.child.checkDropDown();
}

render() {
   return <div>
            <Heade onRef={this.onRef}
          </div>
}

4. Header 组件

componentDidMount() {
   //通过pros接收父组件传来的方法
   this.props.onRef(this)
}

checkDropDown = () => {
  this.setState({
      isShowDropDown: false
  })
}

render() {
	return <header>{ isShowDropDown ? <AAAAAA> :"" }</header>
}
  • 总结:我刚开始做的时候觉得这个方法很蠢,如果层级有很多的话就会无限父级…… 挂载一个child = ref 来接收子组件。但是这个状态几乎只有这一个地方用。所以我就没用 redux 管理来实现 ,"只有遇到 React 实在解决不了的问题,你才需要 Redux 。"

结语

前端react QQ群:788023830 ---- React/Redux - 地下老英雄

前端交流 QQ群:249620372 ---- FRONT-END-JS前端

(我们的宗旨是,为了加班,为了秃顶……,仰望大佬),希望小伙伴们加群一起学习