首页 > 解决方案 > 如何使用引导程序在 React 中显示模式对话框

问题描述

create-react-app我在使用提供样式(无组件)的 vanilla bootstrap 4 库创建的项目中使用 react-16 。

有人可以向我指出一个工作示例,按下按钮我可以打开一个带有引导程序样式的模态对话框吗?

提前致谢。

标签: javascriptreactjsbootstrap-4

解决方案


我有一个使用引导程序的进度代码笔,尽管我没有用引导程序设置我的模式......我实际上在项目的其余部分使用它:https ://codepen.io/manAbl/pen/ eKYVpL?editors=1010

我正在使用以下方法创建模态实例:<div id="modal-root"></div>

他们我正在创建一个与孔反应状态树保持连接的门户,class Modal就像这样:

class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.el = document.createElement('div');
  }

  componentDidMount() {
    modalRoot.appendChild(this.el);
  }

  componentWillUnmount() {
     modalRoot.removeChild(this.el);
  }

  render() {
     return ReactDOM.createPortal(
       this.props.children,
       this.el,
    );
  }
}

并根据状态渲染模态:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showModal: false, 
      };
     this.handleModalVisibility = this.handleModalVisibility.bind(this);
  }

  handleModalVisibility() {
    this.setState({ showModal: !this.state.showModal });
  }
  render() {
    const { showModal } = this.state;

    return (
      <div className="container app-wrapper">
        <ListContainer/>
        <Button onClick={this.handleModalVisibility} title='Add Recipe' />
          { this.state.showModal ? (
          <Modal>
            <InputAddRecipe onClick={this.handleModalVisibility} />
          </Modal> ) : null }
      </div>
    )
  }
}

希望有帮助:)


推荐阅读