天天看點

react 對象渲染_React動态渲染元件(對象配置設定與函數傳回)

我在這裡碰到了一堵磚牆,這意味着我無法完全弄清楚為什麼接下來的兩個版本的代碼行為如此不同。React動态渲染元件(對象配置設定與函數傳回)

在第一個版本,當我初始化一個this.childComponent = (),其道具似乎并不當我改變了Parent的狀态(通過setState())來更新。即使實際調用了setState(),并且Parent的狀态已更新,也會發生這種情況。

在第二個版本中,當我實際初始化一個傳回元件的函數(this.childComponent =() => {return ()})時,一切都像魅力一樣工作,道具被更新。 我正在使用第二個版本(因為它的工作原理),但我想了解為什麼這個工程和第一個不工作。

這裡的子元件:

class Child extends React.Component {

render() {

return (

{this.props.value}

)

}

}

我父元件的下兩個版本:

class Parent extends React.Component {

constructor() {

this.state = {

value: 1

}

this.childComponent = (

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 (

setValue={() => this.setValue()}/>

)

}

}

setValue() {

this.setState({value: 2})

}

render() {

return ({this.childComponent()})

}

}

我試圖簡化代碼,是以我的問題更容易了解。

預先感謝您

+1

在您的第一個(損壞的)版本中,子元件是靜态定義的并且再也不會更改。 –

+1

您在第一種情況下沒有傳回'render(){ return {this.childComponent} }'否則可以使用子元件是靜态的 –

+0

明白了,感謝您的解釋 –