搜尋

首頁  >  問答  >  主體

使用物件數組時,連接 yup 和 react-hook-form 的名稱

<p><br /></p><h4>我正在嘗試透過<code>register</code>將<code>react-hook-form</code>與<code>code>react-hook-form</code>與<code> ;yup</code>的模式連接起來,但遇到了一個錯誤。我的目標是傳遞一個類似<code>exampleArray${index}.exampleProp</code>的名稱,因為我會在循環中渲染輸入框。 </h4> <p>一個簡單的例子:</p> <pre class="brush:php;toolbar:false;">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 ); }</pre> <blockquote> <p>類型'"exampleArr[0].exampleProp"'的參數不能賦值給類型'"exampleArr" | <code>exampleArr.${number}</code> | <code>exampleArr.${ number}.exampleProp</code>'。 </p> </blockquote> <p>codesandbox中的範例:https://codesandbox.io/s/funny-orla-97p8m2?file=/src/App.tsx</p>
P粉743288436P粉743288436550 天前517

全部回覆(1)我來回復

  • P粉312631645

    P粉3126316452023-08-18 20:03:26

    你需要告訴exampleArr.${number}的型別是什麼:

    例如,我剛剛在你的沙盒上測試了一下,它運行得很好:

    <input type="text" {...methods.register("exampleArr[0].exampleProp" as any)} />

    回覆
    0
  • 取消回覆