2015-11-03 60 views
0

我有一個頁面上的員工列表。每個員工項目旁都有一個複選框。這是使用react js開發的。現在,每5秒鐘,我需要根據員工的複選框狀態來檢查並顯示頁面上的多個員工可用/不可用狀態。使用React.render()呈現的兩個組件之間是否可以進行交互?

<div id="container"> <!-- List of employees will be placed here by react.js --> </div>

<div id="status-bar"> 

能否請你告訴我怎麼都的div可以彼此互動,因爲我單獨渲染他們:

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

    React.render(<StatusComponent />, document.getElementById('status-bar')); 

回答

1

我不相信這兩個組件可以在不使用父組件的情況下互相交互。我建議做一個包裝了兩下,像這樣的組件(寫在ES6,而不是在所有測試......剛剛颳起爲例):

class EmployeeModule extends React.component { 

    _countEmployees() { 
    // Magic to get employee count here.. 
    var count = getEmployeeCount(); 
    this.setState({numEmployees: count}); 
    } 

    componentDidMount() { 
    // Count employees every 5 seconds 
    this.interval = window.setInterval(() => this._countEmployees(), 5000)); 
    } 

    componentWillUnmount() { 
    window.clearInterval(this.interval); 
    } 

    render() { 
    return (
     <div className="employee-module-wrapper"> 
     <ListItems /> 
     <StatusComponent numEmployess="{this.state.numEmployees}" /> 
     </div> 
    ) 
    } 

} 

有效,你需要做的是有EmployeeModule手柄兩個組件之間的相互作用。您可以從ListItems模塊中獲取所需的信息,並將其設置爲父模塊的狀態。在_countEmployees內調用setState將觸發對render函數的調用,該函數將在StatusComponent上設置屬性numEmployees,從而更新您的狀態模塊。

希望這會有所幫助

1

我認爲這樣做最好的,更簡單的方法 - 創建商店。您可以使用reduxJS輕鬆創建商店。你也可以在其他塊中包含一個塊,並通過this.props提供你的數據。

相關問題