这几天在写 react的项目,发现antd上大多都是函数组件+antd的形式写的,而笔者使用的是类组件+antd的技术栈,于是写的时候就遇到了一些坑,如下是笔者做的一些记录:
1.表单验证时,前面的红星号 * 出不来。这是因为我们在 <Form.Item >中没有写name属性,name是表单名称,它会作为表单字段 id
前缀使用
2. 弹框中加表单验证, 在 class component 下,可以通过 validateFields 方法触发表单验证
this.formRef.current?.validateFields().then((value: any) => ...).catch((err: any) => ...);
this.formRef 是我们给表单ref的一个名称,通过ref获取表单的数据域, 通过 current下的 validateFields 属性触发表单中所有Form.Item的验证内容 。
3. 在页面渲染的时候,接口有值,但是页面没有回显,可以给表单加入loading,loading的状态由 false→true→false。获取到数据后,loading就会设置为false,然后再渲染表单页面
代码如下:
<Form
name="basic"
ref={this.formRef}
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
initialValues={{ remember: true }}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
autoComplete="off"
>
<Form.Item
label="Username"
name="username"
rules={[{ required: true, message: 'Please input your username!' }]}
>
<Input />
</Form.Item>
<Form.Item
label="Password"
name="password"
rules={[{ required: true, message: 'Please input your password!' }]}
>
<Select
value={formEdit}
onChange={(value) =>
this.setState({
formEdit: value,
})
}
placeholder="请选择Password">
<Select.Option key={item.value} value={item.value}>
{item.label}
</Select.Option>
</Select>
</Form.Item>
<Form.Item wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
formRef = React.createRef<FormInstance>();
// 成功按钮
onFinish = (values: any) => {
this.formRef.current
?.validateFields()
.then((value: any) => {
this.setState({
loading: true,
});
console.log('Success:', values);
/** 调用接口数据 **/
this.setState({
loading: false,
});
})
.catch((err: any) => {
console.log('表单验证失败', err);
});
};
// 失败按钮
onFinishFailed = (errorInfo: any) => {
console.log('Failed:', errorInfo);
};