react 全局公共組件-----動態彈窗 (dialog)
阿新 • • 發佈:2018-09-13
-i script item push cto amp 一個 update []
react 的時候,總是會用到彈窗,並且各種各樣的,一般來說,組件層級嵌套之後,就會出現 z-index層級覆蓋的問題
這個時候,就需要一個公共的彈出層,然後我們將需要展示的組件,放到彈出層裏面
下面是目錄結構:
dialog.jsx代碼
import React, { Component } from ‘react‘; import { is, fromJS } from ‘immutable‘; import ReactDOM from ‘react-dom‘; import ReactCSSTransitionGroup from ‘react-addons-css-transition-group‘; import ‘./dialog.css‘; let defaultState = { alertStatus:false, alertTip:"提示", closeDialog:function(){}, childs:‘‘ } class Dialog extends Component{ state = { ...defaultState }; // css動畫組件設置為目標組件 FirstChild = props => { const childrenArray = React.Children.toArray(props.children); return childrenArray[0] || null; } //打開彈窗 open =(options)=>{ options = options || {}; options.alertStatus = true; var props = options.props || {}; var childs = this.renderChildren(props,options.childrens) || ‘‘; console.log(childs); this.setState({ ...defaultState, ...options, childs }) } //關閉彈窗 close(){ this.state.closeDialog(); this.setState({ ...defaultState }) } renderChildren(props,childrens) { //遍歷所有子組件 var childs = []; childrens = childrens || []; var ps = { ...props, //給子組件綁定props _close:this.close //給子組件也綁定一個關閉彈窗的事件 }; childrens.forEach((currentItem,index) => { childs.push(React.createElement( currentItem, { ...ps, key:index } )); }) return childs; } shouldComponentUpdate(nextProps, nextState){ return !is(fromJS(this.props), fromJS(nextProps)) || !is(fromJS(this.state), fromJS(nextState)) } render(){ return ( <ReactCSSTransitionGroup component={this.FirstChild} transitionName=‘hide‘ transitionEnterTimeout={300} transitionLeaveTimeout={300}> <div className="dialog-con" style={this.state.alertStatus? {display:‘block‘}:{display:‘none‘}}> {this.state.childs} </div> </ReactCSSTransitionGroup> ); } } let div = document.createElement(‘div‘); let props = { }; document.body.appendChild(div); let Box = ReactDOM.render(React.createElement( Dialog, props ),div); export default Box;
dialog.css源碼,,其實就是一個div,遮住層
.dialog-con{ position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.3); }
child.jsx
import React, { Component } from ‘react‘; class Child extends Component { constructor(props){ super(props); this.state = {date: new Date()}; } showValue=()=>{ this.props.showValue && this.props.showValue() } render() { return ( <div className="Child"> <div className="content"> Child <button onClick={this.showValue}>調用父的方法</button> </div> </div> ); } } export default Child;
使用方式:
使用方式,直接調用就可以了,傳入需要展示的子組件,並且給子組件綁定 props,可以實現事件通信
react 全局公共組件-----動態彈窗 (dialog)