antd Design中關於Form表單 setFieldsValue 的使用
阿新 • • 發佈:2021-02-06
技術標籤:react
最近專案使用的是antd Design 4.x 版本,碰到個需要載入後端資料並展示,並且使用者可以進行修改的需求,前端採用的是antd的Form表單來實現
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
在需要的地方進行使用:
this.formRef.current.setFieldsValue({
example: ‘從後臺返回要顯示的值’,
})