2016-07-29 31 views
0

我正在創建一個在React和Electron中的應用程序。我正在嘗試製作一個打開三個TCP套接字的組件,並在全部連接時渲染子組件。它大致如下所示(簡化):關閉時通知孩子的連接狀態的父組件

export class Device extends Component { 
    static propTypes = { 
    port: PropTypes.number.isRequired, 
    host: PropTypes.string.isRequired 
    }; 
    render() { 
    const { port, host, children } = this.props; 
    return (
     <div className="device-mount"> 
     <TCPSocket name="commands" port={port} host={host} /> 
     <TCPSocket name="messages" port={port} host={host} /> 
     <TCPSocket name="routines" port={port} host={host} /> 
     {children} 
     </div> 
    ); 
    } 
} 

的TCP套接字將派出上componentDidMountCONNECTED成功連接時,和所述DISCONNECTED事件CONNECT_ATTEMPT

我發現了一個「不清潔」的解決方案,只需製作一個連接事件,它將使用單個組件並自行觸發所有事件,然後在全部連接後綁定一個處理程序。然而,這似乎不是很好的做法,因爲它不可模塊化。

我的目標是在所有這些TCPSocket組件都已觸發其CONNECTED事件時通知父組件。首先想到的是child context,但實際上,我希望在相反的方向。

如何通知父組件關於多個子組件狀態?

回答

2

給每個他會用它調用回調的名稱和狀態:

export class Device extends Component { 
    static propTypes = { 
    port: PropTypes.number.isRequired, 
    host: PropTypes.string.isRequired 
    }; 

    constructor(props, context) { 
     super(props, context); 

     this.getTCPSocketStatus = this.getTCPSocketStatus.bind(this); 
    } 

    getTCPSocketStatus(name, status) { 
     // whatever you want to do with the status 
    } 
    render() { 
    const { port, host, children } = this.props; 
    return (
     <div className="device-mount"> 
     <TCPSocket name="commands" port={port} host={host} notifyStatus={ getTCPSocketStatus } /> 
     <TCPSocket name="messages" port={port} host={host} notifyStatus={ getTCPSocketStatus } /> 
     <TCPSocket name="routines" port={port} host={host} notifyStatus={ getTCPSocketStatus } /> 
     {children} 
     </div> 
    ); 
    } 
} 

每個孩子都應該再使用回調,例如:

class TCPSocket extends Component { 
    componentDidMount() { 
     const { notifyStatus, name } = this.props; 
     this.props.notifyStatus(name, 'CONNECT_ATTEMPT'); 
    } 

    // implement other status notifications in the same way 
}