2017-09-13 89 views
0

如何将notify作为一个父组件,当任何深度嵌套的children组件dispatches如何在孩子派遣时通知家长?

例如

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

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

<Component1> 
    <Component2> 
     <ComponentThatWillDispatch /> 
    </Component2> 
</Component1> 
+2

你是什么意思的“调度”?所有子代都被渲染后,应该调用父级的componentDidMount方法。各个组件也可以实现'componentDidMount'来调用父方法。但如果你想用这种方式改变某些事物的状态,那就羞愧了。 –

+0

如果您想广播调度,那么您需要将某种功能(例如didDispatch)从父母传递给每个孩子,然后每个孩子都会调用它。 – Mikkel

+0

@RyanWheale:通过调度,我的意思是子组件调用生命循环方法,并在redux商店上执行一个操作。 例如'this.store.dispatch({type:...})' 我不是在谈论渲染。 – DKo

回答

0

有获得从子到父通知两种方式,

  1. ComponentWillReceiveProps,
  2. 从父到子传递一个动作,

ComponentWi llReceiveProps

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

传递行动作为参数

让你的行动会从你的孩子组成部分,但它被触发从家长发送,所以你的父母componwent会知道的功能已被触发

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 ") 
    } 
} 

你^ h大街进口你的组件

+0

对于所有道具,不是“componentWillReceiveProps”,不仅是其子道具? – DKo