经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » React » 查看文章
使用React手写一个对话框或模态框的方法示例
来源:jb51  时间:2019/4/25 10:21:30  对本文有异议

打算用React写对话框已经很长一段时间,现在是时候兑现承诺了。实际上,写起来相当简单。

核心在于使用React的接口React.createPortal(element, domContainer)。该接口将element渲染后的DOM节点嵌入domContainer(通常是document.body),并保证只嵌入一次。

所以,我们可以这样写一个对话框或模态框:

  1. function Dialog() {
  2. return React.createPortal( <div>Dialog contents</div>, document.body )
  3. }

一个新的div会出现在body内部:

一个完整DEMO:


点击运行DEMO

  1. class Modal extends React.Component {
  2. render() {
  3. const {
  4. visible,
  5. onClose
  6. } = this.props
  7. return visible && ReactDOM.createPortal(<StyledModalRoot>
  8. <div className="box">
  9. Content
  10. <br/>
  11. <button onClick={onClose}>Close</button>
  12. </div>
  13. </StyledModalRoot>, document.body)
  14. }
  15. }
  16.  
  17. class App extends React.Component {
  18. state = {
  19. visibleModal: false
  20. }
  21. showModal = () => this.setState( { visibleModal: true } )
  22. handleCloseModal = () => this.setState( { visibleModal: false } )
  23. render() {
  24. const { visibleModal } = this.state
  25. return <div style={{padding: '20px'}}>
  26. <button onClick={ this.showModal }>Show Modal</button>
  27. <Modal visible={visibleModal} onClose={ this.handleCloseModal } />
  28. </div>
  29. }
  30. }
  31.  
  32. const StyledModalRoot = styled.div`
  33. position: fixed;
  34. z-index: 1001;
  35. left: 0;
  36. top: 0;
  37. display: grid;
  38. place-items: center;
  39. width: 100%;
  40. height: 100%;
  41. background: rgba( 0, 0, 0, 0.2 );
  42.  
  43. >.box {
  44. position: relative;
  45. display: grid;
  46. place-items: center;
  47. width: 80%;
  48. height: 80%;
  49. background: white;
  50. border-radius: 10px;
  51. box-shadow: 0px 3px 5px -1px rgba(0,0,0,0.2), 0px 5px 8px 0px rgba(0,0,0,0.14), 0px 1px 14px 0px rgba(0,0,0,0.12);
  52. }
  53. `

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号