Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React |在子组件中执行状态更改时遇到问题_Javascript_Reactjs_Components_Frontend_React Component - Fatal编程技术网

Javascript React |在子组件中执行状态更改时遇到问题

Javascript React |在子组件中执行状态更改时遇到问题,javascript,reactjs,components,frontend,react-component,Javascript,Reactjs,Components,Frontend,React Component,我正在编写一个checkers web应用程序,并通过在组件上放置onclick函数来设置用户交互。我有两个不同的组件,一个是片段,一个是空间。理想情况下,onclick函数链接到父组件中的方法,这些方法解释正在单击的组件的状态,并通过将数据返回到组件或单独的组件来响应。问题是,我不明白在安装所述子组件后如何从父组件向子组件发送数据。我知道您可以使用道具来初始化子组件中的状态,但是在初始化之后,我是否可以从父组件更新子组件?我是新手,所以我还不确定组件间通信是如何工作的。您可以将更新功能传递给c

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

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

母公司

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}来自“React”
导出默认类父扩展组件{
建造师(道具){
超级(道具);
这个州={
“什么?”
}
}
更新方法=(另一个)=>{
this.setState({something:anotherThing})
}
render(){
返回(
{/*我们正在props中传递updateMething函数*/}
this.updateMething(另一个东西)}/>
)
}
}
孩子

import React,{Component}来自“React”
导出默认类ChildComponent扩展组件{
render(){
返回(
{/*我们正在使用updateMething函数更新父状态*/}
this.props.updateMething(“anotherThing”)}>updateParents状态
)
}
}

欢迎使用SO-请查看以确保您获得最佳支持。react是学习react是什么、如何工作以及如何使用它设计UI的绝佳场所。如果您想在这里获得更多帮助,请分享一个代码示例和关于特定范围问题的特定详细信息。
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>
        )
    }
}