事件不会通过反应组件传播

时间:2015-06-19 04:29:44

标签: javascript reactjs

我有以下反应成分:

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

  render() {
    return <button disabled={this.state.disabled} onClick={this.clicked.bind(this)}>Save</button>;
  }

  clicked(event) {
    this.setState({disabled: true});
  }
}

class Form extends React.Component {
  contructor(props) {
    super(props);
    this.state = { foo: "bar" };
  }

  render() {
    return (
      <form onSubmit={this.submit.bind(this)}>
        <input valueDefault={this.state.foo} />
        <Button />
      </form>
    );
  }

  submit(event) {
    event.preventDefault();
    // do some stuff
  }
}

但是,单击该按钮时会触发单击的方法,但不会触发提交方法。有什么方法可以让事件传播?是否有某些原因导致事件不像普通的html表单事件一样传播?

1 个答案:

答案 0 :(得分:0)

由于setState将重新呈现整个组件,因此事件将停在那里,并且无法继续直到祖先形成。相反,您可以在表单的onSubmit中处理按钮禁用。像这样的东西

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

    render() {
      return <button disabled={this.state.disabled}>Save</button>;
    }

    clicked(event) {
      this.setState({disabled: true});
    }
  }

  class Form extends React.Component {
    constructor(props) {
      super(props);
      this.state = { foo: "bar" };
    }

    render() {
      return (
        <form onSubmit={this.submit.bind(this)}>
          <input valueDefault={this.state.foo} />
          <Button ref="button" onSubmit={this.submit.bind(this)}/> <----- Added reference here
        </form>
      );
    }

    submit(event) {
      event.preventDefault();
      var button = this.refs.button; // <---- Added ref to button
      button.setState({disabled:  true}); <---- set disabled state to button
    }
  }

这是一个演示 http://jsbin.com/ginune/edit?html,output