You need to enable JavaScript to run this app. 如何将数组值传递给Formik自定义Select下拉组件
优惠活动
大模型
产品
解决方案
定价
更多

如何将数组值传递给Formik自定义Select下拉组件

Formik 动态下拉选项实现方案

问题根因

此前尝试的方案不生效有两个明确原因:

  • 在MySelect外部遍历数组生成option时,箭头函数使用大括号包裹但没有加return,导致没有返回可渲染的DOM元素,因此下拉框显示为空
  • Formik官方文档的硬编码下标方案是针对多字段数组表单的场景,和单下拉框动态渲染选项的需求不匹配

改造方案

直接改造自定义MySelect组件,兼容静态写死option和动态传入选项数组两种使用场景,无需修改旧表单的已有代码,改造后的完整代码如下:

const MySelect = ({ label, ...props }) => {
    const [field, meta] = useField(props);
      return (
      <div>
        <label htmlFor={props.id || props.name}>{label}</label>
        {/* 兼容两种使用场景:未传options数组时读取子元素作为option,传了则自动遍历生成 */}
        {!props.options ? 
          <select className={props.className} {...field} {...props}  /> 
        : 
          <select className={props.className} {...field} {...props}>
             {props.options.map((item, index) => (
                 <option key={index} value={item.value || item}>
                     {item.label || item} 
                 </option>
             ))} 
           </select>
        }
        {meta.touched && meta.error ? (
          <div className="error">{meta.error}</div>
        ) : null}
      </div>
    );
  };

动态场景调用方式

使用动态数组场景时,直接把后端返回的数组传给options属性即可:

// 假设后端返回的playerList是 ['玩家1', '玩家2', '玩家3'] 格式
<MySelect 
  className="select-input" 
  label="获胜方玩家" 
  name="winningPlayer"
  options={playerList}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 00:06:05