2017-10-05 159 views
1

我試圖在另一個組件中更改我的狀態。我已經道具React - 更改子組件中的狀態

constructor(props) { 
    super(props); 

     this.handleClick = this.handleClick.bind(this); 

     this.state = { 
      isOpen: false 
     }; 
    } 

<MobileContent isOpen={this.state.isOpen} /> 

在我MobileContent組件順利通過了國家我想改變狀態,當我在元素上點擊。

class MobileContent extends Component { 

    render() { 
    if (this.props.isOpen) { 
     return (
      <Grid fluid> 
       <div className="mobileContent"> 
       <Row center="xs"> 
        <Col xs={12}> 
        <span className="button">Hello, world!</span> 
        <span className="close" onClick={this.handleClick} >X</span>    
        </Col>     
       </Row> 
       </div> 
      </Grid> 
     ); 
    } 
    return null; 
    } 
} 

export default MobileContent; 

感謝您的幫助!

+0

你是不是想在單擊關閉按鈕時更新父組件的'isOpen'國家財產?請提供有關「國家」和「元素」的含義的更多信息。 –

+0

我明白了,謝謝@T –

回答

2

如果您希望Child組件通知父項,那麼您應該將一個附加的道具傳遞給該函數的子項。孩子然後可以打電話給他。因此,在父:

constructor(props) { 
    super(props); 

    this.handleClick = this.handleClick.bind(this); 

    this.state = { 
     isOpen: false 
    }; 
} 

<MobileContent isOpen={this.state.isOpen} onClose={this.handleClick}/> 

而且在孩子:

render() { 
    if (this.props.isOpen) { 
     return (
      <Grid fluid> 
       <div className="mobileContent"> 
       <Row center="xs"> 
        <Col xs={12}> 
        <span className="button">Hello, world!</span> 
        <span className="close" onClick={this.props.onClose}>X</span>    
        </Col>     
       </Row> 
       </div> 
      </Grid> 
     ); 
    } 
    return null; 
    }