React 组件之间的通信

Communicate between React Components

我刚开始使用 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 的状态 属性。根据状态,向按钮添加额外的 class。

假设我的页面上有 2 个 OfficeUIButton 组件,如何通过单击第一个按钮激活第二个按钮?

这只是一个虚拟示例,但我需要它作为模态弹出窗口或基于特定操作禁用按钮的示例。

感谢您的帮助。

然后您需要 parent 组件中的状态来控制您的按钮。你可以这样做:

Button 组件,传递 onClick 属性和 active 属性

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

然后在你的 parent 中你需要有一个状态,你将传递给按钮组件和 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.

希望对您有所帮助。

你应该在更高的组件中(为了简单的解释,我们假设它是一个页面),在那里你将存储一个本地商店,你将在哪里传递给每个 UIOFficeButton 一个函数来设置这个更高的组件状态,例如Button1Clicked on 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 中的 disabled 和 onClick 道具,就像在按钮中一样

<button disabled={props.disabled} />

并且不要将 Span 用作按钮。