反应创建模态窗口的最佳实践

时间:2016-06-18 13:24:28

标签: javascript html css user-interface reactjs

如何使用React创建模态窗口?通过模态窗口,我的意思是一个覆盖页面内容的框架。我希望它能够使用网页上的按钮打开,能够通过单击外部区域来关闭它,它将包含一个用户将填写并提交的表单。

React是否为此任务提供了一些生产就绪库,还是应该使用css实现它?同样在容器/代表性组件模式的情况下,我应该将模态组件嵌套在模态开口组件的容器组件内还是模态开口组件本身内?

2 个答案:

答案 0 :(得分:1)

React Modal是一个很棒的图书馆。

答案 1 :(得分:1)

1 - 如果你想在React中编写一个通用的模态组件,你的反应模态组件唯一应该做的就是给出一致的视图,比如包含叠加,设置定位值和所有常见的行为等。 交互决策取决于您如何继续应用程序。例如,我提到的这种方法(1),更适合使用Flux。基本上你有一个商店,并收集其中的所有组件状态相关数据,并且ui状态由传递给你的组件的props管理,而不是调用setState来改变组件的状态。此外,这使您能够在组件外部更改组件的状态。让我用一个例子清楚自己:

import "./modal.scss";

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

  shouldComponentUpdate(nextProps) {
    return !I.is(this.props.data, nextProps.data);
  }

  render() {
    let isOpen = this.props.data.get("isOpen");
    return (
      <div className={`flex middle center modal ${isOpen ? "open" : ""}`}>
      {isOpen ?
        (<div className={`row modal-content ${this.props.size || ""}`}>
          <div className="col-12 middle modal-title">{this.props.title}</div>
          <div className="col-12 modal-body">
            {this.props.body}
          </div>
          <div className="col-12 middle modal-footer">{this.props.footer}</div>
        </div>) : null
      }
      </div>);
  }
}

export default Modal;

和样式文件如:

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 10000;
  padding: 2rem;
  background-color: rgba(0, 0, 0, 0.55);

  .modal-content {
    background-color: white;
    max-height: 80%;
    height: 80%;

    .modal-title {
      padding: 0 2.25rem;
      height: 5rem;
      max-height: 5rem;
      text-transform: uppercase;
      font-size: 1.8rem;
    }

    .modal-body {
      height: calc(100% - 16rem);
      overflow-y: scroll;
      padding: 0 2rem;
    }

    .modal-footer {
      height: 5rem;
      max-height: 5rem;
      padding: 0 2.25rem;
    }
  }
}

您可以将其用作:

<Modal isOpen={/* depends on your parameter */} 
       title="Hello Title" 
       body="Hello Body"
       footer="Hello Footer"
/>

此模态设计仅提供模态的正确视图和基本控件,配置完全取决于您的用法。如果您的应用程序逻辑在模态的其他用法中非常相似,那么您可以自己将它们添加到模态组件中。

相关问题