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

相关推荐
好玩的Matlab(NCEPU)20 分钟前
如何编写 Chrome 插件(Chrome Extension)
前端·chrome
Yan-英杰25 分钟前
Deepseek大模型结合Chrome搜索爬取2025AI投资趋势数据
前端·chrome
Crystal32836 分钟前
app里video层级最高导致全屏视频上的操作的东西显示不出来的问题
前端·vue.js
weixin_4454766838 分钟前
Vue+redis全局添加水印解决方案
前端·vue.js·redis
lecepin39 分钟前
AI Coding 资讯 2025-10-29
前端·后端·面试
余道各努力,千里自同风1 小时前
小程序中获取元素节点
前端·小程序
PineappleCoder1 小时前
大模型也栽跟头的 Promise 题!来挑战一下?
前端·面试·promise
非凡ghost1 小时前
MousePlus(鼠标增强工具) 中文绿色版
前端·windows·计算机外设·软件需求
Moonbit1 小时前
MoonBit Pearls Vol.13:初探 MoonBit 中的 JavaScript 交互
javascript·后端
焚 城1 小时前
EXCEL(带图)转html【uni版】
前端·html·excel