2017-06-13 60 views
2

如何更改道具的价值,如何设置道具, 假设this.props.contact.name的值为John, 我想将其更改为Johnny。 我怎样才能为示例 -如何在反应中更改道具的价值?

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

,除非他们是数组的组件不能更新了自己的道具的全局状态或对象(即使有可能,组件也会更新其自己的道具),但可以更新其状态和子项道具。 –

回答

3

做到这一点

你会改变在父组件的prop,因为这是保持prop本身的价值。这将强制重新呈现任何使用特定prop被更改的子组件。如果你想拦截props发送,你可以使用lifecycle methodcomponentWillReceiveProps

0

我建议而不是改变道具的价值,你可以通过函数到道具,然后更改父组件状态,因此它会改变子组件的道具像

你父组件应该是

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

0
  • 动作示例的组件不能更新其上的道具,他们是不可改变的,在你的 情况下,而不是使用道具可以使用组件的状态。
  • 的组件道具可以更新仅当父组件通过在不同的道具,或者如果你有一家商店,改变应用