简体   繁体   English

以 react-hook-form 记录不断变化的输入字段?

[英]Record a changing input field in react-hook-form?

I'm trying to record values from a form using react-hook-form.我正在尝试使用 react-hook-form 从表单中记录值。 All other situations are working, however I am getting a return value of 'undefined' when I attempt to retrieve data from a value that is also a react hook ( useState ).所有其他情况都在工作,但是当我尝试从也是反应钩子( useState )的值中检索数据时,我得到了“未定义”的返回值。

const [quantity, setQuantity] = useState(1);

const increaseQuantity = () => {
  setQuantity((prevQuantity) => prevQuantity + 1);
};

const decreaseQuantity = () => {
  if (quantity > 1) {
    setQuantity((prevQuantity) => prevQuantity - 1);
  }
};

const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
  console.log(data);
};
<DescriptionButtonsWrapper>
  <CounterContainer>
    <CounterWrapper>
      <CounterButtons onClick={decreaseQuantity}>-</CounterButtons>
    </CounterWrapper>
    <CounterWrapper>
      <CounterInput
        {...register("quantity")}
        placeholder="Quantity"
        id="quantity"
        type="number"
      >
        {quantity}
      </CounterInput>
    </CounterWrapper>
    <CounterWrapper>
      <CounterButtons onClick={increaseQuantity}>+</CounterButtons>
    </CounterWrapper>
  </CounterContainer>
</DescriptionButtonsWrapper>
<DescriptionButtonsWrapper>
  <Btn onClick={handleSubmit(onSubmit)}>Add to Cart</Btn>
</DescriptionButtonsWrapper>

You can use watch to keep track of the field value in the render lifecycle and setValue to update the form value imperatively:您可以使用watch来跟踪渲染生命周期中的字段值,并使用setValue来强制更新表单值:

const { register, watch, handleSubmit, setValue } = useForm({
  defaultValues: {
    quantity: 0
  }
});
const quantity = watch("quantity");
const increaseQuantity = () => setValue("quantity", quantity + 1);
const decreaseQuantity = () => {
  if (quantity > 1) {
    setValue("quantity", quantity - 1);
  }
};

useEffect(() => {
  console.log(quantity);
}, [quantity]);

return (
  <form onSubmit={handleSubmit((data) => alert(JSON.stringify(data)))}>
    <button type="button" onClick={decreaseQuantity}>
      -
    </button>
    <button type="button" onClick={increaseQuantity}>
      +
    </button>
    <input {...register("quantity")} id="quantity" type="number" />

    <input type="submit" />
  </form>
);

代码沙盒演示

References参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM