I am developing a simple edit app page, because the form.item initial value did not update by data, so I want to setFieldsValue
in the antd 4.x, this is my code looks like:
JavaScript
x
49
49
1
import React from 'react'
2
import { Modal, Input, Form } from 'antd'
3
4
export default function EditApp(props) {
5
const { visible, rowData: data = {}, onVisibleChange, onEdit, dispatch } = props
6
7
const [form] = Form.useForm()
8
let formRef = React.createRef()
9
if(formRef.current){
10
formRef.current.setFieldsValue({
11
remark: data?data.remark:''
12
})
13
}
14
15
function onConfirm() {
16
form.validateFields()
17
.then(values => {
18
let localValues = {
19
values,
20
appId: data.app_id
21
}
22
onEdit(localValues)
23
})
24
.catch(info => {
25
console.log('Validate Failed:', info)
26
})
27
}
28
29
function onCancel() {
30
onVisibleChange()
31
}
32
33
return (
34
<>
35
<Modal title='Edit App' visible={visible} onOk={onConfirm} onCancel={onCancel}>
36
<Form form={form} ref={formRef}>
37
<Form.Item
38
label='remark'
39
name='remark'
40
value={data?data.remark:''}
41
>
42
<Input placeholder='Please input remark' />
43
</Form.Item>
44
</Form>
45
</Modal>
46
</>
47
)
48
}
49
To my surprise, the formRef.current
is always null. Am I missing something? what should I do to make the Form.Item value update by data which passed from other component?
Advertisement
Answer
CreateRef work only with class components , you can use the hooks useRef if your react versions support it
JavaScript
1
48
48
1
import React, {useRef} from 'react'
2
import { Modal, Input, Form } from 'antd'
3
4
export default function EditApp(props) {
5
const { visible, rowData: data = {}, onVisibleChange, onEdit, dispatch } = props
6
7
const [form] = Form.useForm()
8
const formRef = useRef();
9
if(formRef.current){
10
formRef.current.setFieldsValue({
11
remark: data?data.remark:''
12
})
13
}
14
15
function onConfirm() {
16
form.validateFields()
17
.then(values => {
18
let localValues = {
19
values,
20
appId: data.app_id
21
}
22
onEdit(localValues)
23
})
24
.catch(info => {
25
console.log('Validate Failed:', info)
26
})
27
}
28
29
function onCancel() {
30
onVisibleChange()
31
}
32
33
return (
34
<>
35
<Modal title='Edit App' visible={visible} onOk={onConfirm} onCancel={onCancel}>
36
<Form form={form} ref={formRef}>
37
<Form.Item
38
label='remark'
39
name='remark'
40
value={data?data.remark:''}
41
>
42
<Input placeholder='Please input remark' />
43
</Form.Item>
44
</Form>
45
</Modal>
46
</>
47
)
48
}