gpt4 book ai didi

reactjs - 如何在 Typescript(输入组件)中使用 React Hook Form

转载 作者:行者123 更新时间:2023-12-03 23:44:59 24 4
gpt4 key购买 nike

该组件没有错误,但在我实际调用输入组件的索引文件中,它有一个错误,因为它不能使用 register = {register}。
有什么不见了?或者有什么问题?
https://codesandbox.io/s/react-hook-form-typescript-xnb1u

最佳答案

好这里的问题:

  • 您需要添加 register到输入组件 Prop 声明中的 Prop
  • 您必须使用 register作为 Prop 传递,而不是用 useForm 创建的新 Prop 在输入组件中
  • 输入元素缺少名称属性

  • 这里的工作 <Input>带注释的组件:
    import React, { InputHTMLAttributes } from "react";
    //import { useForm } from "react-hook-form"; // don't need the import

    interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
    id: string;
    label: string;
    register: any; // declare register props
    }

    const Input: React.FC<InputProps> = ({ id, label, register, ...rest }) => {
    //const { register } = useForm(); // don't use a new `register`, use the one from props

    return (
    <div className="input-block">
    <label htmlFor={id}>{label}</label>
    <br />
    <br />
    {/* you must declare the `name` attribute on the input element */}
    <input name={id} type="text" id={id} ref={register} {...rest} />
    </div>
    );
    };

    export default Input;

    关于reactjs - 如何在 Typescript(输入组件)中使用 React Hook Form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63381635/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com