2017-06-13 35 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
  • 動作示例的組件不能更新其上的道具,他們是不可改變的,在你的 情況下,而不是使用道具可以使用組件的狀態。
  • 的組件道具可以更新僅當父組件通過在不同的道具,或者如果你有一家商店,改變應用