【问题标题】:ReactJS: Trigger event from child in parent componentReactJS:从父组件中的子触发事件
【发布时间】:2020-04-16 00:33:45
【问题描述】:

我有两个组件: 1.Parent 2.Child 子组件中有一个名为 onChange() 的事件,它返回一个值。 我想接收从父组件的 componentDidMount() 中的 OnChange() 返回的值。

例子:

class Parent extends PureComponent {
componentDidMount() {
 let value = CHILD.onChange(); //triggered when ever onChange() 
}
 render(){
      return(
        <Child />
)
  }
}
const Child = () => {

  const onChange = () => {
    const value = 1
    return value;
  };
}

【问题讨论】:

  • 您需要在 Parent 中定义 onChange() 方法,然后在 Child 组件中将其作为 prop 传递并在那里执行。该值可以保存在Parent组件的状态中。
  • 您应该在父组件上定义 onChange 处理程序,并将其作为道具传递给子组件。在子组件中,您接收处理程序并将其设置为适当的事件。

标签: reactjs


【解决方案1】:
class Parent extends PureComponent {


handleChildChange = value => {
 //Do your stuff with value, pass it to the state and take it from there if you like
}


 render(){
      return(
        <Child handleChange={this.handleChildChange} />
)
  }
}
const Child = (props) => {

  const onChange = () => {
    value = 1
    props.handleChange(value);
    }
  };
}

【讨论】:

    猜你喜欢
    • 2017-03-03
    • 2018-10-27
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多