反应|无法在子组件中执行状态更改

时间:2020-08-18 05:37:44

标签: javascript reactjs components frontend react-component

我正在编写一个Checkers Web应用程序,并通过在组件上放置onclick函数来设置用户交互。我有两个不同的组成部分和空间。理想情况下,onclick函数链接到父组件中的方法,这些方法解释被单击的组件的状态并通过将数据返回给该组件或单独的组件来进行响应。问题是,我不理解在安装了子组件之后如何从父组件将数据发送到子组件。我了解您可以使用道具来初始化子组件中的状态,但是无论如何,在初始化之后,我是否仍可以从父组件更新子组件?我是新来的反应者,所以我不确定组件之间的通信如何工作。

1 个答案:

答案 0 :(得分:0)

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

父母

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