【问题标题】:React best practice to create modal windowReact 创建模态窗口的最佳实践
【发布时间】:2016-10-20 05:31:50
【问题描述】:

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

React 是否有一些 生产就绪 库来完成这项任务,还是我应该使用 css 来实现它?同样在容器/代表性组件模式的情况下,我应该将模态组件嵌套在模态打开组件的容器组件内还是在模态打开组件本身内?

【问题讨论】:

  • 如果你想使用 Materialize 和 React Bootstrap,它们都是非常好的模态。

标签: javascript html css user-interface reactjs


【解决方案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"
/>

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

【讨论】:

  • 在你的 Modal 组件的shouldComponentUpdate 方法中,你有return !I.is(this.props.data, nextProps.data);,但是I 指的是什么? AFAIK,它是未定义的......
  • prop 的相等性检查。没关系,取决于你使用什么,例如,如果你使用 immutable.js,你可以使用那个表单
【解决方案2】:

React Modal 是一个很好的库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 2019-01-20
    • 2015-07-23
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    相关资源
    最近更新 更多