【问题标题】:React | Having trouble enacting state changes in child component反应 |在子组件中执行状态更改时遇到问题
【发布时间】:2020-12-07 06:36:19
【问题描述】:

我正在编写一个跳棋网络应用程序,并通过在组件上放置 onclick 功能来设置用户交互。我有两个不同的组件和空间。理想情况下,onclick 函数链接到父组件中的方法,这些方法解释被单击的组件的状态,并通过将数据返回给组件或单独的组件来响应。问题是,我不明白如何在安装所述子组件后从父组件向子组件发送数据。我知道您可以使用道具来初始化子组件中的状态,但是无论如何我可以在此初始化之后从父组件更新子组件吗?我是新手,所以我还不确定组件间的通信是如何工作的。

【问题讨论】:

  • 欢迎来到 SO - 请查看how to ask a good question 以确保您得到最好的支持。
  • React docs 是开始学习 React 是什么、它如何工作以及如何使用它设计 UI 的好地方。如果您在此处需要更多帮助,请分享Minimal, Complete, and Reproducible 代码示例和特定范围问题的具体细节。

标签: javascript reactjs components frontend react-component


【解决方案1】:

您可以将更新功能传递给孩子,我希望这会有所帮助。

父母

import React, { Component } from 'react'

export default class Parent extends Component {
    constructor(props) {
        super(props);
        this.state={
            something:""
        }
    }
    updateSomething = (anotherThing) => {
        this.setState({something:anotherThing})
    }
    render() {
        return (
            <div>
                {/* we are passing updateSomething function in props*/}
            <ChildComponent updateSomething={(anotherThing)=>this.updateSomething(anotherThing)}/>
            </div>
        )
    }
}

孩子

import React, { Component } from 'react'

export default class ChildComponent extends Component {
    render() {
       
        return (
            <div>
                {/* we are using updateSomething function to update parents state*/}
                <button onClick={()=>this.props.updateSomething("anotherThing")}>Update Parents state</button>
            </div>
        )
    }
}

【讨论】:

    猜你喜欢
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 2017-02-18
    • 2019-09-17
    • 2018-11-03
    • 2020-03-13
    • 2020-05-03
    相关资源
    最近更新 更多