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

React表单setValue覆盖placeholder值,useFieldArray正常问题求助

问题描述

用户编辑表单从API获取数据后,useFieldArray管理的字段数组可正常赋值,但调用setValue给firstName、lastName等单个字段赋值时,输入框的placeholder被覆盖。

表单更新代码:

const handleGetUser = (user: UsersDataSourceModel) => {
    if (!_.isEmpty(user)) {
        setValue('firstName', user.firstName, {shouldTouch: true});
        setValue('lastName', user.lastName, {shouldTouch: true});
        setValue('emailId', user.emailId, {shouldTouch: true});
        if (user.roles.length) {
            user.roles.map((role, index) => {
                setValue(`userCountryRoleMappings.${index}.region`, role.region);
                setValue(`userCountryRoleMappings.${index}.roleId`, role.roleId);
                setValue(`userCountryRoleMappings.${index}.countryId`, role.countryId);
                setValue(`userCountryRoleMappings.${index}.neverExpireRole`, role.neverExpireRole);
                setValue(`userCountryRoleMappings.${index}.roleExpiryDate`, role.roleExpiryDate);
                setValue(`userCountryRoleMappings.${index}.isReadOnly`, role.isReadOnly);
            })
        }
    }
}

表单显示情况:
表单显示情况

解决方案

1. 处理空值赋值问题

如果user.firstName等字段为null或undefined,直接调用setValue会将字段值设为null/undefined,部分UI组件会因此隐藏placeholder。可以给字段设置默认空字符串:

setValue('firstName', user.firstName ?? '', {shouldTouch: true});
setValue('lastName', user.lastName ?? '', {shouldTouch: true});
setValue('emailId', user.emailId ?? '', {shouldTouch: true});

2. 改用reset批量初始化表单

react-hook-form的reset方法更适合批量设置表单初始值,能避免多次setValue带来的副作用,同时保证placeholder正常显示:

const handleGetUser = (user: UsersDataSourceModel) => {
    if (!_.isEmpty(user)) {
        const formData = {
            firstName: user.firstName ?? '',
            lastName: user.lastName ?? '',
            emailId: user.emailId ?? '',
            userCountryRoleMappings: user.roles.map(role => ({
                region: role.region,
                roleId: role.roleId,
                countryId: role.countryId,
                neverExpireRole: role.neverExpireRole,
                roleExpiryDate: role.roleExpiryDate,
                isReadOnly: role.isReadOnly
            }))
        };
        reset(formData, {shouldTouch: true});
    }
}

3. 检查UI组件绑定逻辑

确保输入框组件正确通过react-hook-form的register或Controller绑定字段值,避免手动处理value导致的placeholder异常。例如:

// 使用register
<input {...register('firstName')} placeholder="First Name" />

// 或使用Controller(针对受控组件)
<Controller
    name="firstName"
    control={control}
    render={({ field }) => (
        <input {...field} placeholder="First Name" />
    )}
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:31:04