标题 antd Design Form setFieldsValue的使用
最近项目使用的是antd Design 4.x 版本,碰到个需要加载后端数据并展示,并且用户可以进行修改的需求,前端采用的是antd的Form表单来实现
组件加载的时候向后端请求数据
componentDidMount() {
gainCountry().then(res => {
// 这里进行数据请求
......
})
}
form表单要回填数据一般会想到的是initialValues,但是这是适用于初始化值的时候,官方文档的原话:“initialValues 不能被 setState 动态更新,你需要用 setFieldsValue 来更新” 。搜索一番setFieldsValue的使用,基本上都是:this.props.form.setFieldsValue, props自带form,试用之后发现报错,this.props下没有form,这个好像只适用于antd 3.x
解决
antd4.x 中使用setFieldsValue 是通过ref来进行操作,如下所示:
class Index extends Component{
constructor(props) {
super(props)
this.state = { }
}
// 创建一个ref
formRef = React.createRef()
render(){
return{
{/* 绑定到Form身上*/}
<Form ref={this.formRef}>
<Form.Item name="example">
<Input />
</Form.Item>
</Form>
}
}
}
export default BaseInfo
在需要的地方进行使用:
// example 为Form.Item中的name
this.formRef.current.setFieldsValue({
example: ‘从后台返回要显示的值’,
})
结束语
官方文档中都是有相关说明的,setFieldsValue 的使用我是在文档中的一个例子中找到的,碰到问题的时候还是要多阅读文档
对于函数的类
//获取回显信息并显示
const [fields, setFields] = useState([]);
setFields([
{
name: ['name'],
value: data.workName,
},
{
name: ['desc'],
value: data.workDesc,
},
])
<Form
fields={fields}
>
<FormItem
name="name"
rules={[
{
required: true,
message: "请输入工单名称",
},
]}
>
<Input
placeholder={"工单名称"}
/>
</FormItem>
1、使用
{this.props.form.getFieldDecorator("key",{})(<Input />)}
3、设值
this.props.form.setFieldsValue({
key: '123',
});
2、取值
this.props.form.validateFields((err, values) => {
if (!err) {
console.log("表单信息", values);
}
});
3、清空值
this.props.form.resetFields();