如何更改道具的价值,如何设置道具, 假设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
,除非他们是数组的组件不能更新了自己的道具的全局状态或对象(即使有可能,组件也会更新其自己的道具),但可以更新其状态和子项道具。 –