React 供应商选择组件 - 使用Ant Design渲染Select并与父组件Form同步数据

1、安装Ant Design的相关依赖:

shell 复制代码
npm install antd @ant-design/icons

2、编写SupplierSelect组件的代码如下:

javascript 复制代码
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 (
    <Select
      value={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同步数据

javascript 复制代码
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的值,从而保持数据的同步性。

相关推荐
Vicky&James11 分钟前
WPF到Web的无缝过渡:英雄联盟客户端项目OpenSilver迁移实战
前端·wpf
m0_7482336415 分钟前
RabbitMQ 进阶
android·前端·后端
不想有bug的小菜鸟23 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
m0_7482386324 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
u01005596025 分钟前
前端代理,解决跨域问题讲解
前端
quitv30 分钟前
react脚手架配置别名
前端·javascript·react.js
m0_5287238139 分钟前
前端如何进行性能优化
前端·性能优化
化作繁星40 分钟前
在 Vue 3 中,如何缓存和复用动态组件
前端·vue.js·缓存
一粒沙-1 小时前
iOS 将GIF图分享至微信
前端·ios
graywen1 小时前
从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
前端