2016-03-30 75 views
0

我想弄清楚如何在子組件狀態改變時設置樣式到父組件
考慮一個場景,其中我們有一個包含菜單和邊欄作爲其靜態元素的容器組件加上 子組件。當點擊菜單時,相應的組件將呈現爲子組件。如何根據子組件的狀態更改父組件樣式元素?

我使用的是反應路由器嵌套的絕對路徑如下

<Route component={ home } > 
     <Route path="menu-1" component={ menu-1 } /> 
     <Route path="menu-2" component={ menu-2 } /> 
     <Route path="menu-3" component={ menu-3 } /> 

家組件內我有話如下:

<div className='root'> 
     <menuComponent /> 
     <sideBarComponnent /> 
     {this.props.children} 

    </div> 

,你可以看到我不能通過回調功能的兒童組件 菜單1,菜單2我沒有問題,但點擊菜單3並渲染它的組件在內容標籤,
我需要給它的全長,並設置側欄顯示爲無 WHI樂邊欄的容器組件已使我無法控制它的孩子,一個內部的正常做法

林尋找一種方式,它可以是能夠處理它帶回家組件內部

回答

0

你可以在子組件的道具中添加功能。 當你需要改變父類型時,你可以在子組件中調用這個函數。 該函數將改變父組件的狀態並改變它的樣式。

實施例:

class Parent extends React.Component { 
    constructor(props, context) { 
     super(props, context); 
     this.state = { 
      backgroundColor: 'yellow' 
     } 
    } 

    onChangeStyle(backgroundColor) { 
     this.setState({ 
      backgroundColor: backgroundColor 
     }) 
    } 

    render() { 
     return <div style={{backgroundColor: this.state.backgroundColor, padding: 10}}> 
      <Child onChangeParentStyle={this.onChangeStyle.bind(this)}/> 
     </div> 
    } 
} 

class Child extends React.Component { 
    onClick() { 
     this.props.onChangeParentStyle('red'); 
    } 
    render() { 
     return <span onClick={this.onClick.bind(this)} style={{background: 'white', cursor: 'pointer'}}> 
      Change parent style 
     </span> 
    } 
} 

React.render(<Parent />, document.getElementById('container')); 

Example on JSFiddle

+0

感謝您詳細的解答,@Alesandr 其實我知道回調函數,但我的情況是不同的 我已更新問題 –

+0

您可以使用React.cloneElement dd道具進入兒童。 –

0

可以使用this.props.location.pathname內部componentWillMount如下:

componentWillMount(){ 
let propPlainUrl = /[a-zA-Z]+/g.exec(this.props.location.pathname); 
       this.setState({ 
        activeMenu: menuItems.indexOf(propPlainUrl[0]) + 1 
      }); 

可以使用componentWillMount來設置活性初始值鍵根據選定的路線菜單

上面的代碼只是在初始化組件的初始渲染時解決了問題 但是如果您希望在組件更新點擊菜單事件時保持過程更新?

您可以使用如下略有變化相同的代碼:

componentWillReceiveProps(nextProps){ 
    let propPlainUrl = /[a-zA-Z]+/g.exec(nextProps.location.pathname); 
    this.setState({ 
     activeMenu: menuItems.indexOf(propPlainUrl[0]) + 1 
    }); 
    } 

```

componentWillReceiveProps將讓你在組件更新更新狀態

相關問題