如何更改props的值,如何使用setProps方法,假设this.props.contact.name的值为John,我想将其更改为Johnny。
我该怎么做?
例如:
changeValue(){
this.props.contact.name='Johnny'
}
如何更改props的值,如何使用setProps方法,假设this.props.contact.name的值为John,我想将其更改为Johnny。
我该怎么做?
例如:
changeValue(){
this.props.contact.name='Johnny'
}
prop
,因为它保存了prop
本身的值。这将强制重新渲染使用特定prop
的任何子组件。如果您想在发送props
时拦截它们,可以使用生命周期方法componentWillReceiveProps
。 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>
);
}
}
this.props.fadeImage.bind(this)
时要使用 bind
?@Dhaval Patel - henhenthis.setState(...)
https://facebook.github.io/react/docs/state-and-lifecycle.html