我將 getValues 與 react-hook-form 一起使用,然后在用戶超過限制時嘗試在錯誤訊息中呈現文本欄位的字符長度。當我第一次單擊提交時,我看到 0/1046 個字符,然后第二次看到正確的數字。
const titleValue = getValues('title')
const descriptionValue = getValues('description')
<TextField
name='title'
defaultValue=''
label='Title*'
control={control}
css={{}}
help={
errors.title?.type === 'required' || errors.title?.type === 'maxLength'
? errors.title.message
: undefined
}
aria-label='title'
rules={{
required: { value: true, message: 'Required' },
maxLength: {
value: 1024,
message: `${titleValue?.length || 0}/1024 maximum character length exceeded`,
},
}}
/>

uj5u.com熱心網友回復:
react-hook-form 提供了答案https://github.com/react-hook-form/react-hook-form/discussions/7668
validate: (value) => {
if (value.length >= 10) {
// this will give you the correct value for your error message
return `Please, enter a title with less than 10 characters (${value.length}/10)`;
}
}
}}```
uj5u.com熱心網友回復:
請參考useForm - getValues
用于讀取表單值的優化助手。watch 和 getValues 的區別在于 getValues 不會觸發重新渲染或訂閱輸入更改。
useForm - watch似乎更適合您的需求。
這將監視指定的輸入并回傳它們的值。它對于確定要渲染的內容很有用。
const titleValue = watch('title')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/422457.html
標籤:
