【问题标题】:Record a changing input field in react-hook-form?以 react-hook-form 记录不断变化的输入字段?
【发布时间】:2021-12-09 08:07:28
【问题描述】:

我正在尝试使用 react-hook-form 从表单中记录值。所有其他情况都有效,但是当我尝试从一个也是反应挂钩 (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>

【问题讨论】:

    标签: javascript reactjs react-hooks react-hook-form


    【解决方案1】:

    您可以使用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>
    );
    

    参考

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 2022-07-30
      • 2021-01-20
      • 2021-05-25
      • 2020-07-07
      • 2021-01-26
      • 1970-01-01
      • 2022-06-13
      • 2022-11-02
      相关资源
      最近更新 更多