javascript - ReactJS,如何从 CHILD 更新 PARENT 的状态

标签 javascript reactjs react-props

<分区>

如果我有一个设置状态并将其传递给子级的父级,我如何才能从子级更改父级的状态?

    // parent
    this.state = {
        status: 'doing...'
    }

    // child render
    <div>{this.props.state.status}</div>
    // child function triggered by an onClick
    update = () => this.setState(status: 'finished');

这样的东西是行不通的

    // parent
    this.state = {
        status: this.props.state.status
    }

    // or child
    this.props.setState(status: 'finished');

    // or child
    getDerivedStateFromProps(nextProps) {
       console.log('I'm never executed)
       this.setState({ status: nextProps.state.status});
    }

最佳答案

这里说的

How to update the state of child component from parent?

对于选项 2,我不明白的是如何通过 props 传递函数。

如果在 child 那里我定义了<CHILD message={this.message}然后我可以用 this.props.message 调用那个函数在 child 中。

关于javascript - ReactJS,如何从 CHILD 更新 PARENT 的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52892009/

相关文章:

javascript - 为什么 in 运算符对于未定义的属性返回 true?

javascript - 继承Javascript类方法

javascript - 在最新的mui 中LoadingButton 不见了?

javascript - 将 React 中的功能组件转换为基于类的组件

javascript - 如何在 React 中使用 props 来处理参数?

javascript - Jquery 选择器可以找到隐藏的元素(显示 : none;), 如何禁用这种情况?

javascript - 在 mongoose 中查询 id 后的第一个项目数?

javascript - Reactjs 将键盘语言自动更改为波斯语

reactjs - 在 React 中,为什么更改非状态 Prop 不会提示重新渲染?

javascript - React Native 中的自定义按钮组件不接受 Prop