2016-12-02 77 views
0

我剛剛開始使用React,它似乎只是美麗的創建用戶界面,但是,我確實遇到組件間通信問題。React組件之間的溝通

我有一個非常簡單的反應組件,代表一個按鈕:

import React from 'react'; 

export default class OfficeUIButton extends React.Component { 

    constructor(props) { 
    super(props); 
    this.state = { 
     active: false, 
    }; 

    // Bind the event handlers. 
    this.onMouseDownEventHandler = this.onMouseDownEventHandler.bind(this); 
    this.onMouseUpEventHandler = this.onMouseUpEventHandler.bind(this); 
    } 

    onMouseDownEventHandler() { 
    this.setState({ 
     active: true 
    }); 
    } 

    onMouseUpEventHandler() { 
    this.setState({ 
     active: false 
    }); 
    } 

    render() { 
    return <div className={"officeui-button" + (this.state.active ? ' active': '')} onMouseDown={this.onMouseDownEventHandler} 
       onMouseUp={this.onMouseUpEventHandler}> 
       <span className="officeui-button-label">{this.props.text}</span> 
      </div> 
    } 
} 

該組件有一個名爲active的狀態屬性。根據狀態,將一個附加類添加到按鈕中。

我們假設我的頁面上有2個這樣的OfficeUIButton組件,我怎麼能通過點擊第一個按鈕使第二個按鈕處於活動狀態?

這只是一個虛擬的例子,但我需要這個例如模式彈出,或基於某些行動禁用按鈕。

感謝您的幫助。

+1

[提起狀態](https://facebook.github.io/react/docs/lifting-state-up.html)。如果多個組件在某種程度上相互依賴,那麼該州應該由其共同的祖先之一擁有。 –

+0

可能的重複:[ReactJS兩個組件通信](https://stackoverflow.com/questions/21285923/reactjs-two-components-communicating) – oklas

回答

1

然後,您需要在父組件中控制按鈕的狀態。你可以這樣做:

按鈕組件,你通過的onClick道具和活躍道具

class Button extends React.Component { 
    render(){ 
    let disabled = this.props.active ? "disabled" : ""; 
    return(
     <div><button onClick={this.props.onClick} disabled={disabled}>Button</button></div> 
    ) 
    } 
} 

然後在你的父母,你需要有您將傳遞給按鈕組件的狀態和onClick功能:

class Test extends React.Component { 
    constructor(props){ 
     super(props); 

     this.state = { 
     active: false 
     } 
    } 

    handleClick(event){ 
     this.setState({active: !this.state.active}); 
    } 

    render(){ 
     return (
     <div> 
      <Button onClick={this.handleClick.bind(this)}/> 
      <Button active={this.state.active}/> 
     </div> 
    ) 
    } 
} 

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

這是fiddle

希望這會有所幫助。

+0

我忘了提及,如果沒有父元素? – Complexity

+1

你會在哪裏渲染按鈕組件? – Boky

+0

它直接在頁面上,而不在另一個組件內。經過一番閱讀,我想我需要一個像Flux這樣的事件系統,還是這是一個誤解? – Complexity

1

你應該在更高的組件(讓我們來簡單解釋一下,它是一個頁面),你將在哪裏存儲一個本地存儲以及你將傳遞給每個UIOFficeButton的函數,這個函數將設置這個更高的組件狀態,例如Button1點擊true,並將該狀態發送給其他組件。

class Test extends React.Component { 
    constructor(props){ 
     super(props); 
     this.state = { 
      buttonOneClicked: false 
     } 
     } 

handleClickButtonOne =() => this.setState({buttonOneClicked: true}); 

render(){ 
     return (
      <div> 
       <OfficeUIButton onClick={this.handleClickButtonOne} /> 
       <OfficeUIButton disabled={this.state.buttonOneClicked} /> 
      </div> 
     ) 
    } 
} 

不要忘了真正處理您OfficeUIButton殘疾和道具的onClick像按鈕

<button disabled={props.disabled} /> 

,不使用跨度爲一個按鈕。

+0

我忘了提及,如果沒有父元素呢? – Complexity

+0

使用redux這樣的東西,因爲如果他們在相同的水平,那麼現在意味着彼此之間現實的連接。 – Shiroo