[英]Link react-hook-form Controller to a state value
我正在嘗試將 react-hook-form Controller 鏈接到 state 值,但它沒有呈現該值。
import { Controller, useForm } from "react-hook-form";
...
// here is my fields values
const [ addBill, setAddBill ] = useState({
debitAmt: '',
invoiceNumber: '',
memo: '',
invoiceDate: moment().format('YYYY-MM-DD'),
});
// here is how I'm rendering the Controller Input
<FormGroup className="mr-10 mb-10">
<Label for="debitAmt" className="mr-sm-10">Debit Amt</Label>
<Controller
render={ ({value}) => {
return (
<NumberFormat
value={value}
thousandSeparator={true}
prefix={"$"}
onValueChange={(v) => {
setAddBill({...addBill, debitAmt: v.floatValue === undefined ? '' : v.floatValue})
}}
/> );
}}
name="debitAmt"
id="debitAmt"
variant="outlined"
defaultValue={addBill.debitAmt}
value={addBill.debitAmt}
getInputRef={register({ required: true })} aria-invalid={errors.debitAmt ? "true" : "false"}
control={control}
className="form-control"
style={setErrorStyle(errors.debitAmt)}
/>
{errors.debitAmt && (
<span style={{ color: "red" }} role="alert">required</span>
)}
</FormGroup>
然后,當我打電話時:
setAddBill({
...addBill,
debitAmt: 10
});
它不會更新 NumberFormat 的值。 如何將 Controller 連接到 state 變量?
正如您在Controller 文檔中看到的那樣,Controller 的渲染方法procue value 和 onChange 屬性。 你應該這樣使用:
<Controller
render={ ({value, onChange}) => {
return (
<NumberFormat
value={value}
thousandSeparator={true}
prefix={"$"}
onValueChange={(v) => {
setAddBill({...addBill, debitAmt: v.floatValue === undefined ? '' : v.floatValue});
onChange(v);
}}
/> );
}}
name="debitAmt"
id="debitAmt"
variant="outlined"
defaultValue={addBill.debitAmt}
value={addBill.debitAmt}
getInputRef={register({ required: true })} aria-invalid={errors.debitAmt ? "true" : "false"}
control={control}
className="form-control"
style={setErrorStyle(errors.debitAmt)}
/>
在 React-hook-form 中,默認情況下,您不需要控制輸入狀態。 如果您讓 RHF 保存它,您可以使用Watch API或使用 handleSubmit 提交表單來檢索 state 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.