从父组件获取模态触发

时间:2019-03-22 04:55:26

标签: reactjs

Noob问题在这里。如何从父组件触发Modal的切换组件?我希望在父组件上单击按钮时打开模式。该按钮将提交一个表单,一旦提交表单,我希望模态触发。我正在尝试使其在function handleSubmit(e)

中启动

子组件:Modal.jsx

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

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

  toggle() {
    this.setState(prevState => ({
      modal: !prevState.modal
    }));
  }

  render() {
    return (
      <div>
        <Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
          <ModalHeader toggle={this.toggle}>Modal title</ModalHeader>
        </Modal>
      </div>
    );
  }
}

路径:Parent.jsx

export default function ForgotPassword() {
  function handleSubmit(e) {
    e.preventDefault();
  }

  return (
    <div className="container h-100">
      <ModalExample toggle />
      <button onClick={this.handleSubmit}>Open modal</button>
    </div>
  );
}

2 个答案:

答案 0 :(得分:3)

您可以使用以下引用

export default function ForgotPassword() {
      function handleSubmit(e) {
        e.preventDefault();
      }

      return (
        <div className="container h-100">
          <ModalExample  ref={instance => { this.child = instance; }}  />
          <button onClick={() => { this.child.toggle(); }}>Open modal</button>
        </div>
      );
    }

答案 1 :(得分:0)

也许有更好的方法,但是我做的方法是将toggle函数拉到父类,并将函数和状态值都传递给props中的模式。< / p>

然后您可以在模式中调用props函数以切换其显示,尽管这会将您的纯组件变成有状态组件。

子组件:Modal.jsx

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

  render() {
    return (
      <div>
        <Modal isOpen={this.props.modal} toggle={this.props.toggle} className={this.props.className}>
          <ModalHeader toggle={this.props.toggle}>Modal title</ModalHeader>
        </Modal>
      </div>
    );
  }
}

父母:Parent.jsx

class ForgotPassword() extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      modal: false
    };
    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState(prevState => ({
      modal: !prevState.modal
    }));
  }

  return (
    <div className="container h-100">
      <ModalExample toggle={this.toggle} modal={this.state.modal} />
      <button onClick={this.handleSubmit}>Open modal</button>
    </div>
  );
}