弹框高阶组件
在使用atnd组件化弹框时,我们在书写的时候,每次都要控制弹框的visible,包括点击”确定“时,我们需要从弹框内容中获取表单数据,以及需要处理错误返回时弹框的交互,或者时弹框内容的一些变换,这就使代码看起来很混乱,各种不同的功能相互混合,耦合度高,而且每次都需要处理弹框的交互状态,有重复的劳动力。于是这就需要我们单独封装一个组件,在组件中单独处理弹框的功能,暴露出弹框组件的方法,让弹框内容部分的组件使用,让该组件专注业务内容的书写。
高阶组件,可以称之为HOC,即该组件入参一个组件,将该组件经过处理后,返回的组件已经具备了我们所需要的各个功能,常见的处理包括添加方法、包裹一层dom元素。 主要目的为了提高可复用性。
下面来看看弹框高阶组件的处理
const isFunction = (data) => typeof data === 'function';
export default (WrappedComponent) => {
return class ModalHoc extends PureComponent{
static propTypes = {
modalProps: PropTypes.object
};
state = {
visible: false,
saving: false,
fullScreenStyle : undefined,
};
doOk = null;
doShow = null;
doCancel = null;
componentDidCatch(e){
console.error(e);
}
componentDidMount(){
this.modalControl.show(this.doShow);
}
handleOk = () => isFunction(this.doOk) && this.doOk();
handleCancel = () => this.modalControl.close(this.doCancel);
/**
* 弹框的控制器
* @type {
{show: (function(*=): *), close: (function(*=): *), showSaving: (function(*=): *), hideSaving: (function(*=): *), registerOk: ModalHoc.modalControl.registerOk, registerCancel: ModalHoc.modalControl.registerCancel}}
*/
modalControl = {
show: (cb) => this.setState({ visible: true }, () => isFunction(cb) && cb()),
close: (cb) => this.setState({ visible: false, saving: false }, () => isFunction(cb) && cb()),
showSaving: (cb) => this.setState({ saving: true }, () => isFunction(cb) && cb()),
hideSaving: (cb) => this.setState({ saving: false }, () => isFunction(cb) && cb()),
registerShow: (cb) => {
if(isFunction(cb)){
this.doShow = cb;
}