register将react-hook-form与yup的模式连接起来,但是遇到了一个错误。我的目标是传递一个类似于exampleArray${index}.exampleProp的名称,因为我将在循环中渲染输入框。一个简单的例子:
import * as yup from "yup";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
const schema = yup.object().shape({
exampleArr: yup.array().of(
yup.object().shape({
exampleProp: yup.string()
})
)
});
type FormValues = yup.InferType<typeof schema>;
export default function App() {
const methods = useForm<FormValues>({
resolver: yupResolver(schema)
});
return (
<input type="text" {...methods.register("exampleArr[0].exampleProp")} /> // error here
);
}
类型'"exampleArr[0].exampleProp"'的参数不能赋值给类型'"exampleArr" |
exampleArr.${number}|exampleArr.${number}.exampleProp'。
codesandbox中的示例:https://codesandbox.io/s/funny-orla-97p8m2?file=/src/App.tsx
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你需要告诉
exampleArr.${number}的类型是什么:例如,我刚在你的沙盒上测试了一下,它运行得很好:
<input type="text" {...methods.register("exampleArr[0].exampleProp" as any)} />