【发布时间】:2020-05-16 12:50:45
【问题描述】:
我正在使用具有子组件的组件对 React js 进行 POC 编码。据我所知,除了通过从子组件到子组件的回调函数之外,没有其他方法可以从子组件更新父组件的状态父组件。就我而言,我尝试将父级的状态传递给子级并将它们直接设置为子级作为道具(this.props.)。我注意到如果我更改子级的状态,则父级的状态也在更新。我有点困惑。有人可以帮忙吗? 这是我的代码。
index.js
ReactDOM.render(<App2/>,document.getElementById('root'));
App2.js - 父组件
import React from 'react'
import ScreenTest From './ScreenTest'
class App2 extends React.Component{
state={
address : {
houseName:'1234 House Name'
}
}
render(){
return(
<ScreenTest parentState={this.state} address={this.state.address} />
)
}
}
ScreenTest.jsx - 子组件
import React from 'react';
class ScreenTest extends React.Component{
state={
parentState: this.props.parentState,
address : this.props.address
}
clickButton = () =>{
let addressTemp = this.state.address;
addressTemp.city= "Kerala";
this.setState({
address:addressTemp
})
}
render(){
console.log("To view the state when the screen renders",this.state)
return(
<a onClick={this.clickButton}>Click me to update the state and re render </a>
)
}
}
代码说明: 我正在调用具有子组件 ScreenTest 的 App2 组件。我将 App2 的 currentState 传递给 ScreenTest。在 ScreenTest 中,我根据作为道具传递的值设置状态。在 ScreenTest 中,单击时我有一个锚标记,更新 ScreenTest 的“地址”状态并重新渲染屏幕。当屏幕重新渲染时,我检查状态以查看 parentState 也使用新地址更新(即添加了城市)。
请告诉我 parentState 是如何受到它的影响的。我有点糊涂了。
【问题讨论】:
标签: reactjs react-props react-component