首页 > React如何动态的插入一个组件?

React如何动态的插入一个组件?

比如在做登陆页面的时候,提交后台返回用户名或者密码错误,如何动态的插入一个弹窗组件。


在state里加个值为false,需要显示时setState改为true。现实的地方根据这个值来做就行了。

render 里面:

{this.state.showError && <MyErrorComponent />}

其实你想问的应该是如何实现弹窗吧, 如果是的话方法有几种:

第一种:古老的方式,利用现有的 jquery 组件,Modal.show(config). (好处是重用以前的组件);
第二种:显示隐藏弹出窗,如果使用了 bootstrap ,可以直接利用 bootstrap 的 modal 样式,显示隐藏的方法有两种,第一种使用 class, 第二种使用 jsx 条件判断是否渲染弹窗 div。(这种方式有限制,渲染出来的 div 会被包含在局部 div 中,如果这个 div 是 overflow:hidden 的那就麻烦了)

render() {
    return <div>
        <div class="show|hide modal">
        </div>
     </div>
}

第三种:使用 React 的一些第三方 Model 组件,如 ant.design 的 modal http://ant.design/components/modal

render() {
    return (
      <div>
        <Button type="primary" onClick={this.showModal}>显示对话框</Button>
        <Modal title="第一个 Modal" visible={this.state.visible}
          onOk={this.handleOk} onCancel={this.handleCancel}
        >
          <p>对话框的内容</p>
          <p>对话框的内容</p>
          <p>对话框的内容</p>
        </Modal>
      </div>
    );
  }

第四种: 自己实现一个 Modal 组件, 实现方式参考 khan 学院的 React modal http://khan.github.io/react-components/#modal ,基本的思路是抽象出一个 LayeredComponentMixin, 这个 Mixin 的实现见 https://github.com/Khan/react-components/blob/master/js/layered-component-mixin.jsx 基本上就是在 body 的尾部渲染出一个新的 div ,这个div 会包含 Modal 的内容。

【热门文章】
【热门文章】