为了实现一个页面中的两个功能,所以添加两个Modal弹窗,Button触发,配合Form表单使用。
但点击确认后的回调函数却是会互相干扰,如何区分两个不同的表单呢?
点击确定后……无反应
结果另一个表单触发了确定事件……
代码结构如下:
const CollectionCreateForm = Form.create()(
class RegistrationForm extends React.Component {
state = {
confirmDirty: false,
autoCompleteResult: [],
};
render() {
const {visible, onCancel, onCreate, currentRole, form} = this.props;
const {getFieldDecorator} = form;
const formItemLayout = {
labelCol: {
xs: {span: 24},
sm: {span: 6},
},
wrapperCol: {
xs: {span: 24},
sm: {span: 14},
},
};
return (
<Modal
visible={visible}
title="创建用户"
okText="确定"
onCancel={onCancel}
onOk={onCreate}
>
<Form
style={{paddingTop:"20px"}}
onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="用户名"
id="userName"
hasFeedback
>
{getFieldDecorator('userName', {
rules: [{
required: true,
message: '请输入正确的用户名!',
whitespace: true,
max: 32,
pattern: /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/
}],
})(
<Input/>
)}
</FormItem>
</Form>
</Modal>
);
}
}
);
const CollectionModifyForm = Form.create()(
class ModifyForm extends React.Component {
state = {
confirmDirty: false,
autoCompleteResult: [],
}
render() {
const {visible,theCurrentRole, onModifyCancel, onModifyCreate, form} = this.props;
const {getFieldDecorator} = form;
let currentRole = JSON.stringify(theCurrentRole)
const formItemLayout = {
labelCol: {
xs: {span: 24},
sm: {span: 6},
},
wrapperCol: {
xs: {span: 24},
sm: {span: 14},
},
};
return (
<Modal
visible={visible}
title="修改用户信息"
okText="确定"
onCancel={onModifyCancel}
onOk={onModifyCreate}
>
<Form
style={{paddingTop:"20px"}}
onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="用户名"
id="username"
hasFeedback
>
{getFieldDecorator('label', {
rules: [{
required: true,
message: '请输入正确的用户名!',
whitespace: true,
max: 32,
pattern: /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/
}],
})(
<Input/>
)}
</FormItem>
</Form>
</Modal>
);
}
}
);
class Settings extends Component {
//初始化balabala ……
//业务逻辑相近,样例只写了一份,除了props和函数命名之外,代码都是一样。
handleCancel = () => {
this.setState({visible: false});
};
handleCreate = () => {
const form = this.form;
form.validateFields((err, values) => {
if (err) {
return;
}
this.setState({createLoading: true});
console.log('Received values of form: ', values);
form.resetFields();
this.setState({
visible: false,
createLoading: false
});
});
};
saveFormRef = (form) => {
this.form = form;
};
render() {
return(
<div>
<Button
onClick={this.showModifyModal}
>修改</Button>
<CollectionModifyForm
ref={this.saveFormRef}
visible={this.state.visible}
onCancel={this.handleCancel}
onCreate={this.handleCreate}
/>
//业务逻辑相近,所以除了props和函数命名之外,代码都是一样。
<Button
onClick={this.showModifyModal}
>修改</Button>
<CollectionModifyForm
ref={this.saveModifyFormRef}
visible={this.state.modifyVisible}
onModifyCancel={this.handleModifyCancel}
onModifyCreate={this.handleModifyCreate}
/>
</div>
)
}
}
所以,如何在基本相同的业务逻辑下区分两个不同的表单?
两个表单分开验证好了,不要都用this.form,可以用this.form_1,this.form_2