如何在React中更改属性值?

11

如何更改props的值,如何使用setProps方法,假设this.props.contact.name的值为John,我想将其更改为Johnny。

我该怎么做?

例如:

changeValue(){
  this.props.contact.name='Johnny'
}

5
一个组件不能更新它自己的props,除非这些props是数组或者对象(即使可能,一个组件更新它自己的props也是一种反模式),但是它能够更新它自己的state以及它子组件的props。 - Dhaval Patel
3个回答

7
您需要在父组件中更改prop,因为它保存了prop本身的值。这将强制重新渲染使用特定prop的任何子组件。如果您想在发送props时拦截它们,可以使用生命周期方法componentWillReceiveProps

4
我建议不要改变props的值,而是将函数传递到props中,然后更改父组件的状态,这样它就会更改子组件的props,例如:
您的父组件应该是:
  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 - henhen

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接