【问题标题】:React | Having trouble enacting state changes in child component反应 |在子组件中执行状态更改时遇到问题
【发布时间】:2020-12-07 06:36:19
【问题描述】:
我正在编写一个跳棋网络应用程序,并通过在组件上放置 onclick 功能来设置用户交互。我有两个不同的组件和空间。理想情况下,onclick 函数链接到父组件中的方法,这些方法解释被单击的组件的状态,并通过将数据返回给组件或单独的组件来响应。问题是,我不明白如何在安装所述子组件后从父组件向子组件发送数据。我知道您可以使用道具来初始化子组件中的状态,但是无论如何我可以在此初始化之后从父组件更新子组件吗?我是新手,所以我还不确定组件间的通信是如何工作的。
【问题讨论】:
标签:
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>
)
}
}