想要改变输入背景颜色,如果输入没有使用use -form从react-hook-form验证



我正在尝试使用react-hook-form验证一个简单的表单。我正在处理验证部分很好,我目前唯一的问题是,我想改变输入字段的背景颜色,同时添加一个小的弹出文本,如果字段没有验证。我能够做的文本弹出部分很容易,但似乎无法找到一种方法来改变输入的背景颜色。我只是想知道如何在{errors}方法中有一个P标签,并在同一方法中设置一定的状态。例如,如果我只想要文本弹出框,我可以使用以下命令:

<input name="name" {...register("name",{required:true}}/>
{errors.name && <p>Type a name</p>}

但是我如何在那个方法中设置一个状态呢?例如,如果我有一个状态:

const [background, setBackground] = useState(false);

我应该如何使用setBackground,类似这样:

{errors.name && <p>Type a name</p> && {setBackground(true)}}

下面不起作用,控制台说我渲染太多了,但我很好奇是否有类似的解决方案。非常感谢任何建议!以下是codesandbox链接,以更好地理解我想要实现的目标:https://codesandbox.io/s/aged-lake-ieyctq?file=/src/App.js

你可以通过使用react的useEffect钩子来实现它,如果在name字段中检测到错误,它将运行你的setBackground函数:

useEffect(() => {
if (errors.name) {
setBackground(true); // sets background in case there was an error
} else {
setBackground(false); // unsets background in case there is no error
}
}, [errors.name]);

看到它在你的分叉沙箱上工作:https://codesandbox.io/s/mystifying-nobel-tpc0ee

最新更新