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

React Final Form:如何在带PrefixedField的Wizard中使用initialValues

问题原因与解决方案

问题出在initialValues的结构不匹配PrefixedField生成的字段路径:

你的PrefixedField会把name="nomeCompleto"转换成实际的表单字段名dadosCliente.nomeCompleto,但你传入的initialValues是平级的{ nomeCompleto: "Lois S" },表单无法找到对应嵌套路径的值,所以初始值无法生效。

修正步骤

  1. 调整initialValues的结构,将字段值嵌套在对应前缀的对象中:
<Wizard
  initialValues={{
    dadosCliente: { // 新增前缀对应的嵌套对象
      nomeCompleto: "Lois S"
    }
  }}
  onSubmit={onSubmit}
>
  <Wizard.Page>
    <FieldPrefix prefix="dadosCliente">
      <label htmlFor="nomeCompleto" className="form-label">
          Nome Completo
      </label>
      <PrefixedField
        name="nomeCompleto"
        className="form-control"
        component="input"
        type="text"
        placeholder="Nome Completo"
        validate={required}
      />
      {/* 注意:这里Error组件的name需要匹配实际字段路径 */}
      <Error name="dadosCliente.nomeCompleto" />
    </FieldPrefix>
  </Wizard.Page>
</Wizard>
  1. 修正Error组件的name属性:
    原代码中Error name="firstName"是错误的,需要改成实际的字段路径dadosCliente.nomeCompleto,或者你也可以封装一个PrefixedError组件来复用前缀逻辑,和PrefixedField保持一致:
const PrefixedError = ({ name, ...props }) => (
  <FieldPrefixContext.Consumer>
    {prefix => <Error name={`${prefix}.${name}`} {...props} />}
  </FieldPrefixContext.Consumer>
);
// 使用时直接写 <PrefixedError name="nomeCompleto" /> 即可

补充说明

你的PrefixedField实现是正确的,核心问题就是初始值的结构要和字段的实际路径完全对应。React Final Form会根据字段的完整路径去initialValues中查找对应的值,路径不匹配就无法渲染初始内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:35:10