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

相关推荐
coderYYY3 分钟前
git push报错Authentication failed for ‘xxx’也不会弹要求输入用户名密码的最终解决方法
前端·git·gitee·github
l1t41 分钟前
QWen 3.5plus总结的总结基准测试结果的正确方法
前端·数据库
gCode Teacher 格码致知1 小时前
Javascript及Python提高:将对象的键值对转换为数组元素的方式以及两种语言的对比-由Deepseek产生
javascript·python
Hello.Reader1 小时前
Spark Connect 快速入门远程连接 Spark 集群实战
javascript·ajax·spark
kyriewen111 小时前
为什么我的代码在测试环境跑得好好的,一到用户电脑就崩?原来凶手躲在地址栏旁边
开发语言·前端·javascript·chrome·ecmascript·html5
小北方城市网1 小时前
JavaScript 实战 —— 实现一个简易的 TodoList(适合前端入门 / 进阶)
开发语言·前端·javascript
是上好佳佳佳呀1 小时前
【前端(二)】CSS 知识梳理:从编写位置到选择器优先级
前端·css
倾颜2 小时前
我是怎么把单 Tool Calling 升级成多 Tool Runtime 的
前端·后端·langchain
清汤饺子2 小时前
Superpowers:给 AI 编程 Agent 装上"工程化超能力"
前端·javascript·后端
踩着两条虫2 小时前
AI驱动的Vue3应用开发平台 深入探究(十三):物料系统之区块与页面模板
前端·vue.js·人工智能·架构·系统架构