页面中有大量的form表单,但是不是所有的自定义表单都能满足我们的需求,很有可能需要自定义组件去解决问题,那么自定义组件如何获取antd的value值呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { Form, Input } from 'antd';
import { useEffect } from 'react';

const App = () => {
const [form]= Form.useForm();

useEffect(() => {
form.setFieldsValue({
a: {
b: {
c: 'ccc'
}
},
d: {
e : 'eee'
}
})
}, []);

return (
<Form form={form}>
<Form.Item name={['d', 'e']}>
<Input/>
</Form.Item>
</Form>
)
}
export default App;

这代码熟悉吧!是不是经常写?

这是 antd 的 Form 组件的用法:

通过 useForm 拿到 form 对象,设置到 Form 组件里,然后用 form.setFieldsValue 设置的字段值就能在 Form.Item 里取到。

Form.Item 只需要在 name 里填写字段所在的路径就行,也就是 [‘d’, ‘e’] 这个。

有的同学可能会问了,为啥这里只设置了个 name,它下面的 Input 就有值了呢?

我们让 Form.Item 渲染一个自定义的组件试一下,比如这样:

1
2
3
4
5
const MyInput = (props) =>{
return <div>
<Input>
</div>
}
1
2
3
4
5
6
7
return (
<Form form={form}>
<Form.Item name={['d', 'e']}>
<MyInput/>
</Form.Item>
</Form>
)

通过给自定义组件打断点,可以看到,组件内部传入了 id、value、onChange 等参数进来,

这就是为啥 Input 能有值,因为传入了 value 参数。

而且变化了也能同步到 fields,因为传入了 onChange 参数。

有的时候我们要对保存的值做一些修改,就可以这样写:

1
2
3
4
5
6
7
8
function MyInput(props) {
const { value, onChange } = props;
console.log(form.getFieldsValue())
function onValueChange(event) {
onChange(event.target.value.toUpperCase());
}
return <Input value={value} onChange={onValueChange}></Input>
}

所以说,Form.Item 会给子组件传入 value、onChange 参数用来设置值和接受值的改变,同步到 form 的 fields。

以下是我个人经常使用的上传图片的组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import React, { useEffect, useState } from 'react'
import { message, Upload } from "antd";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";

const defaultUrl = ""
const imageURL = ""


const UploadImg = (props: any) => {
const {value, onChange} = props;
const [loading, setLoading] = useState(false);


const handleChange = (info: any) => {
if (info.file.status === "uploading") {
setLoading(true);
return;
}
if (info.file.status === "done") {
const url = info.file.response.data.url;
onChange && onChange(url);
setLoading(false);
}
};


const beforeUpload = (file: any) => {
const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
if (!isJpgOrPng) {
message.error("只支持 JPG/PNG 文件!");
}
const isLt2M = file.size / 1024 / 1024 < 5;
if (!isLt2M) {
message.error("图片必须小于5MB!")
}
return isJpgOrPng && isLt2M;
};

return (
<Upload
name="file"
// customRequest={customRequest}
listType="picture-card"
className="avatar-uploader"
showUploadList={false}
action={defaultUrl}
beforeUpload={beforeUpload}
onChange={handleChange}
>
{value ? (
<img src={imageURL + value} alt="avatar" style={{ width: "100%" }} />
) : (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div style={{ marginTop: 8 }}>点击上传</div>
</div>
)}
</Upload>
)
}


export default UploadImg

感谢您的阅读,本文由 李经纶 版权所有。如若转载,请注明出处:李经纶个人博客(https://chinalijinglun.github.io//2023/02/22/表单自定义组件/