antd设置表单的某个字段的值
1、创建form的实例
const [formObj] = ProForm.useForm()
2、给form绑定创建的实例
<Form form={formObj} / >
3、设置表单的值
export default function index(props) {
const [formObj] = ProForm.useForm()
function dataStr(val) {//获取到子组件传过来的值
formObj.setFieldsValue({ "details": val })
}
return (
<Form form={formObj}>
<Input name="details"/>
</Form>
)
}
//这里的details是要设置的表单的某个字段的name,val是要设置的具体值。我这里的val是子组件传过来的。
注意 useForm 是 React Hooks 的实现,只能用于函数组件,如果是在 class component 下,你也可以通过 ref 获取数据域。
import { Form, Input, Button, Select } from 'antd';
import { FormInstance } from 'antd/es/form';
const { Option } = Select;
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
const tailLayout = {
wrapperCol: { offset: 8, span: 16 },
};
class Demo extends React.Component {
formRef = React.createRef<FormInstance>();
onGenderChange = (value: string) => {
switch (value) {
case 'male':
this.formRef.current!.setFieldsValue({ note: 'Hi, man!' });
return;
case 'female':
this.formRef.current!.setFieldsValue({ note: 'Hi, lady!' });
return;
case 'other':
this.formRef.current!.setFieldsValue({ note: 'Hi there!' });
}
};
onFinish = (values: any) => {
console.log(values);
};
onReset = () => {
this.formRef.current!.resetFields();
};
onFill = () => {
this.formRef.current!.setFieldsValue({
note: 'Hello world!',
gender: 'male',
});
};
render() {
return (
<Form {...layout} ref={this.formRef} name="control-ref" onFinish={this.onFinish}>
<Form.Item name="note" label="Note" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item name="gender" label="Gender" rules={[{ required: true }]}>
<Select
placeholder="Select a option and change input text above"
onChange={this.onGenderChange}
allowClear
>
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
>
{({ getFieldValue }) =>
getFieldValue('gender') === 'other' ? (
<Form.Item
name="customizeGender"
label="Customize Gender"
rules={[{ required: true }]}
>
<Input />
</Form.Item>
) : null
}
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
<Button htmlType="button" onClick={this.onReset}>
Reset
</Button>
<Button type="link" htmlType="button" onClick={this.onFill}>
Fill form
</Button>
</Form.Item>
</Form>
);
}
}
ReactDOM.render(<Demo />, mountNode);
margin-right: 8px;
}
|