1、安装Ant Design的相关依赖:
npm install antd @ant-design/icons
2、编写SupplierSelect组件的代码如下:
import React, { useEffect, useState } from 'react';
import { Select } from 'antd';
import axios from 'axios';const { Option } = Select;const SupplierSelect = ({ value, onChange }) => {const [data, setData] = useState([]);useEffect(() => {fetchData();}, []);const fetchData = async () => {try {const response = await axios.get('https://api.example.com/suppliers');setData(response.data);} catch (error) {console.error(error);}};const handleChange = (selectedValue) => {onChange(selectedValue);};return (<Selectvalue={value}onChange={handleChange}style={{ width: '100%' }}placeholder="Select a supplier">{data.map((item) => (<Option key={item.id} value={item.id}>{item.name}</Option>))}</Select>);
};export default SupplierSelect;
3、在父组件中,可以使用SupplierSelect组件并与Form同步数据
import React, { useState } from 'react';
import { Form, Button } from 'antd';
import SupplierSelect from './SupplierSelect';const MyForm = () => {const [form] = Form.useForm();const [selectedSupplier, setSelectedSupplier] = useState(null);const onFinish = (values) => {console.log('Form values:', values);};return (<Form form={form} onFinish={onFinish}><Form.Item label="Supplier" name="supplier"><SupplierSelect value={selectedSupplier} onChange={setSelectedSupplier} /></Form.Item><Form.Item><Button type="primary" htmlType="submit">Submit</Button></Form.Item></Form>);
};export default MyForm;
这样,可以在父组件中使用SupplierSelect组件,并将其与Form同步数据。通过调用setSelectedSupplier函数来更新父组件中selectedSupplier的值,从而保持数据的同步性。