简介
在后台管理系统中,一个表格列表可能需要好多个弹窗用来进行添加、编辑数据。最近维护公司代码,发现老项目的代码,弹窗页面和列表页面写在一起,往往一个页面就写了几千行的代码,看得好不舒服。让人烦躁还不说,我们还需要维护好多个Modal的visible状态。
类似如下代码
<div>
<Modal visible={isShowAddModal}>
添加数据代码...
</Modal>
<Modal visible={isShowEditModal}>
编辑数据代码...
</Modal>
<Modal visible={isShowDetailsModal}>
详情数据代码...
</Modal>
<div/>
这时候就需要维护三个状态,且添加编辑等逻辑都写在同一js中,导致一个页面中几千行代码,增加维护成本。
解决方案
父调子方法,将modal状态和逻辑封装在子组件中,父组件调用子组件的方法打开弹窗。
父组件
import React, { Component } from 'react';
import { Modal} from 'antd';
export default class AddDataModal extends Component {
constructor(props) {
super(props);
this.AddDataModal = React.createRef();
}
componentDidMount() {
this.AddDataModal.current.openModal()
}
render() {
return (
<div>
<AddDataModal ref={this.AddDataModal } />
</div>
);
}
}
子组件
import React, { Component } from 'react';
import { Modal} from 'antd';
export default class AddDataModal extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
};
}
componentDidMount() {}
// 打开弹窗
openModal = () => {
this.setState({
visible: true,
});
};
// 确定按钮
handleOk = () => {
this.setState({
visible: false,
});
};
// 取消按钮
handleCancel = () => {
this.setState({
visible: false,
});
};
render() {
return (
<div>
<Modal
title="添加数据弹窗"
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
footer={null}
width={1000}
destroyOnClose={true}
>
添加数据逻辑
</Modal>
</div>
);
}
}
新问题
当我在子组件中使用From的时候,需要在子组件中添加如下代码
@Form.create()
添加了之后,就获取不带子组件中的openModal方法了
官方文档是这样写的
class CustomizedForm extends React.Component { ... }
// use wrappedComponentRef
const EnhancedForm = Form.create()(CustomizedForm);
<EnhancedForm wrappedComponentRef={(form) => this.form = form} />
this.form // => The instance of CustomizedForm
这时候就不需要定义ref了
使用 wrappedComponentRef
子组件不变,父组件如下
父组件
import React, { Component } from 'react';
import { Modal} from 'antd';
export default class AddDataModal extends Component {
constructor(props) {
super(props);
// this.AddDataModal = React.createRef();
}
componentDidMount() {
this.AddDataModal.openModal()
}
render() {
return (
<div>
<AddDataModal wrappedComponentRef={form => (this.AddDataModal = form)} />
</div>
);
}
}