如何在任何孩子发送时通知家长?

时间:2017-09-13 00:07:51

标签: reactjs redux react-redux

当任何深层嵌套的notify组件children时,如何dispatches父组件?

e.g。

class ParentComponent extends Component {
    render() {
        return (
            <div>
                {this.props.children}
            </div>
        );
    }
}

请注意,儿童可以有任何深度,例如

<Component1>
    <Component2>
        <ComponentThatWillDispatch />
    </Component2>
</Component1>

1 个答案:

答案 0 :(得分:0)

有两种方式可以从子级通知父级,

  
      
  1. ComponentWillReceiveProps,
  2.   
  3. 将行动从父母传递给孩子,
  4.   

ComponentWillReceiveProps

它将返回以前的道具和新的道具,以便通知组件

将操作作为参数传递

这样你的行为就会从你的子组件触发,但它会从父组件中调出,这样你的父组件就会知道该函数已被触发

class ParentComponent extends Component {
    constructor() {
      this.myAction= this.myAction.bind(this); 
    } 
    render() {
        return (
            <div>
            <Component1>
                <Component2 >
                    <ComponentThatWillDispatch myaction={this.myAction}/>
                </Component2>
            </Component1>
            </div>
        );
    }
    myAction(){
      alert("Called ")
    }
}

您必须导入组件

相关问题