如何更改道具的價值,如何設置道具, 假設this.props.contact.name的值爲John, 我想將其更改爲Johnny。 我怎樣才能爲示例 -如何在反應中更改道具的價值?
changeValue(){
this.props.contact.name='Johnny'
}
如何更改道具的價值,如何設置道具, 假設this.props.contact.name的值爲John, 我想將其更改爲Johnny。 我怎樣才能爲示例 -如何在反應中更改道具的價值?
changeValue(){
this.props.contact.name='Johnny'
}
做到這一點
你會改變在父組件的prop
,因爲這是保持prop
本身的價值。這將強制重新呈現任何使用特定prop
被更改的子組件。如果你想攔截props
發送,你可以使用lifecycle methodcomponentWillReceiveProps
。
道具是不可變,這意味着你不能改變它們! https://facebook.github.io/react/docs/components-and-props.html
如果要保存一個新的價值構建它作爲一個國家,並使用this.setState(...)
https://facebook.github.io/react/docs/state-and-lifecycle.html
我建議而不是改變道具的價值,你可以通過函數到道具,然後更改父組件狀態,因此它會改變子組件的道具像
你父組件應該是
class SendData extends React.Component{
constructor(props) {
super(props);
this.state = {
images: [
'http://via.placeholder.com/350x150',
'http://via.placeholder.com/350x151'
],
currentImage: 0
};
this.fadeImage=this.fadeImage.bind(this);
}
fadeImage(e) {
e.preventDefault();
this.setState({currentImage: (this.state.currentImage + 1) % this.state.images.length})
}
render()
{
return(
<FadeImage images={this.state.images} currentImage={this.state.currentImage} fadeImage={this.fadeImage}/>
)
}
}
ÿ我們的孩子組件應該像
class FadeImage extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="image">
<CSSTransitionGroup
transitionName="example"
transitionEnterTimeout={300}
transitionLeaveTimeout={300}
>
<section>
<button className="button" onClick={this.props.fadeImage.bind(this)}>Click!</button>
<img src={this.props.images[this.props.currentImage]}/></section>
</CSSTransitionGroup>
</div>
);
}
}
請點擊這裏Demo
,除非他們是數組的組件不能更新了自己的道具的全局狀態或對象(即使有可能,組件也會更新其自己的道具),但可以更新其狀態和子項道具。 –