You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用React Final Form实现表单选择后API联动下拉框

React Final Form 实现依赖型联动下拉框

核心逻辑

通过watch方法监听第一个下拉框的字段值变化,触发API请求获取第二个下拉框的选项,用状态管理选项列表,再渲染到第二个下拉框中。

完整代码示例

import React, { useState, useEffect } from 'react';
import { Form, Field } from 'react-final-form';

// 替换成你的实际后端接口调用
const fetchSecondDropdownOptions = async (selectedValue) => {
  const response = await fetch(`/api/second-options?value=${selectedValue}`);
  return response.json();
};

const DependentDropdownForm = () => {
  // 存储第二个下拉框的选项
  const [secondOptions, setSecondOptions] = useState([]);
  // 加载状态,用于提示用户
  const [isLoading, setIsLoading] = useState(false);

  return (
    <Form
      onSubmit={(values) => {
        console.log('表单提交值:', values);
        // 这里处理实际的表单提交逻辑
      }}
      render={({ handleSubmit, form }) => {
        // 实时监听第一个下拉框的选中值(字段名设为firstDropdown)
        const firstValue = form.watch('firstDropdown');

        // 第一个选项变化时,请求第二个下拉框的选项
        useEffect(() => {
          if (!firstValue) return;

          const getOptions = async () => {
            setIsLoading(true);
            try {
              const options = await fetchSecondDropdownOptions(firstValue);
              setSecondOptions(options);
              // 清空第二个下拉框的选中值,避免残留无效选项
              form.change('secondDropdown', undefined);
            } catch (error) {
              console.error('获取选项失败:', error);
              setSecondOptions([]);
            } finally {
              setIsLoading(false);
            }
          };

          getOptions();
        }, [firstValue, form]);

        return (
          <form onSubmit={handleSubmit}>
            {/* 第一个硬编码选项的下拉框 */}
            <div>
              <label>第一个下拉框</label>
              <Field name="firstDropdown" component="select" required>
                <option value="">请选择</option>
                <option value="option1">选项1</option>
                <option value="option2">选项2</option>
                <option value="option3">选项3</option>
              </Field>
            </div>

            {/* 第二个依赖型下拉框 */}
            <div>
              <label>第二个下拉框</label>
              <Field name="secondDropdown" component="select" disabled={!firstValue || isLoading} required>
                <option value="">请选择</option>
                {isLoading ? (
                  <option value="">加载中...</option>
                ) : (
                  secondOptions.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))
                )}
              </Field>
            </div>

            <button type="submit" disabled={isLoading}>提交</button>
          </form>
        );
      }}
    />
  );
};

export default DependentDropdownForm;

关键细节说明

  • 监听字段变化:使用form.watch('firstDropdown')实时获取第一个下拉框的选中值,配合useEffect触发API请求。
  • 状态管理选项:用useState存储第二个下拉框的选项,请求成功后更新状态,React会自动重渲染组件。
  • 重置第二个字段:当第一个选项变化时,调用form.change('secondDropdown', undefined)清空第二个下拉框的选中值,避免选中无效选项。
  • 加载状态处理:添加isLoading状态,禁用第二个下拉框和提交按钮,提升用户体验。
  • 错误处理:API请求失败时清空选项列表,避免展示错误数据。

内容的提问来源于stack exchange,提问作者Cesare

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 14:32:21