我在這裏碰到了一堵磚牆,這意味着我無法完全弄清楚爲什麼接下來的兩個版本的代碼行爲如此不同。React動態渲染組件(對象分配與函數返回)
在第一個版本,當我初始化一個this.childComponent = (<ChildComp />)
,其道具似乎並不當我改變了Parent
的狀態(通過setState()
)來更新。即使實際調用了setState()
,並且Parent
的狀態已更新,也會發生這種情況。
在第二個版本中,當我實際初始化一個返回組件的函數(this.childComponent =() => {return (<ChildComp />)}
)時,一切都像魅力一樣工作,道具被更新。 我正在使用第二個版本(因爲它的工作原理),但我想了解爲什麼這個工程和第一個不工作。
這裏的子組件:
class Child extends React.Component {
render() {
return (
<button onClick=(this.props.setValue())>
{this.props.value}
</button>
)
}
}
我父組件的下兩個版本:
class Parent extends React.Component {
constructor() {
this.state = {
value: 1
}
this.childComponent = (
<Child value={this.state.value}
setValue={() => this.setValue()}/>
)
}
setValue() {
this.setState({value: 2})
}
render() {
return ({this.childComponent})
}
}
2.(該this.childComponent
是現在是一個返回反應元素的函數)
class Parent extends React.Component {
constructor() {
this.state = {
value: 1
}
this.childComponent =() => {
return (
<Child value={this.state.value}
setValue={() => this.setValue()}/>
)
}
}
setValue() {
this.setState({value: 2})
}
render() {
return ({this.childComponent()})
}
}
我試圖簡化代碼,所以我的問題更容易理解。
預先感謝您
在您的第一個(損壞的)版本中,子組件是靜態定義的並且再也不會更改。 – pscl
您在第一種情況下沒有返回'render(){ return {this.childComponent} }'否則可以使用子組件是靜態的 –
明白了,感謝您的解釋 –