2016-10-22 66 views
1

我是JavaScript新手,並且使用react.js創建一個前端應用程序。以下是我無法編碼的場景。 我想顯示一個項目列表,當我單擊列表中的任何一個項目時,我只看到所選項目的詳細信息並刪除項目的視圖。我嘗試使用react-router庫,但react-router以嵌套方式工作,子組件的細節在父組件(項目列表)下呈現。它不隱藏父組件。隱藏父反應組件,當你點擊一個子組件

回答

1

您可以將函數傳遞給父組件的子項onClick,並處理該函數中的隱藏事件。一個簡單的工具看起來像這樣:

class Parent extends React.Component { 
    constructor() { 
     super(...arguments); 
     this.state = {hide: false}; 
    } 
    handleChildClick() { 
     this.setState({hide: true}); 
    } 
    render() { 
     const {hide} = this.state; 
     if (hide) { 
      return null; 
     } 
     return <Child onClick={this.handleChildClick.bind(this)} />; 
    } 
} 

class Child extends React.Component { 
    render() { 
     const {onClick} = this.props; 
     return <button onClick={onClick}>Hide Parent</button>; 
    } 
} 
+0

謝謝Philip。但是,我能夠使用反應組件**上下文**屬性以更乾淨的方式實現它。我添加了一個onClick回調(nextPage)給父元素。/* onClick回調*/nextPage(){ let url = this.context.router.push(url); }/*聲明上下文*/ .contextTypes = { router:React.PropTypes.object.isRequired, }; –

相關問題