reactjs - 如何在 React with Typescript 中使用和指定 Generic Hooks?

标签 reactjs typescript react-hooks typescript-generics

我正在尝试创建一个通用 Hook 来处理按钮输入元素,它返回输入值数组、绑定(bind)对象和重置处理程序。

组件

import React, { useState } from "react";
import { useInput } from "../services/FormInputHooks";

export type AddTransactionProps = {};

export const AddTransaction: React.FC<AddTransactionProps> = () => {
    const [text, bindText, resetText] = useInput<string>("");
    const [amount, bindAmount, resetAmount] = useInput<number>(0.0);

    return (
        <>
            <h3>Add new transaction</h3>
            <form>
                <div className="form-control">
                    <label htmlFor="text">Text</label>
                    <input
                        type="text"
                        {...bindText}
                        placeholder="Enter text.."
                    />
                </div>
                <div className="form-control">
                    <label htmlFor="amount">
                        Amount <br />
                        (negative - expense, positive - income)
                    </label>
                    <input
                        type="number"
                        {...bindAmount}
                        placeholder="Enter amount.."
                    />
                </div>
                <button className="btn"> Add Transaction</button>
            </form>
        </>
    );
};

export default AddTransaction;

Hook

import { useState } from "react";

export function useInput<T>(
    initialValue: T
): [T, any, React.Dispatch<React.SetStateAction<T>>] {
    const [value, setValue] = useState<T>(initialValue);

    const reset = () => {
        setValue(initialValue);
    };

    const bind = {
        value,
        onChange: e => {
            setValue(e.target.value);
        }
    };

    return [value, bind, reset];
}

我面临的问题

Parameter 'e' implicitly has an 'any' type.  TS7006

    12 |     const bind = {
    13 |         value,
  > 14 |         onChange: e => {
       |                   ^
    15 |             setValue(e.target.value);
    16 |         }
    17 |     };

虽然我已经为绑定(bind)对象指定了 any 类型,但它显示了上述错误。我什至尝试使用以下代码来指定返回类型。

[T, {T: onChange: (e: any) => void}, React.Dispatch<React.SetStateAction<T>>]

最佳答案

问题不在于您为钩子(Hook)返回值定义的类型,而是绑定(bind)对象没有任何类型注释,因此其 onChange 方法的 e 参数将隐含地是任何。

修复其类型注释的一种可能解决方案:

import { useState, ChangeEventHandler } from "react";

interface ResetFunction {
    (): void
}

interface Bind<T> {
  value: T,
  onChange: ChangeEventHandler<any>
}

export function useInput<T>(
    initialValue: T
): [T, Bind<T>, ResetFunction] {
    const [value, setValue] = useState<T>(initialValue);

    const reset = () => {
        setValue(initialValue);
    };

    const bind: Bind<T> = {
        value,
        onChange: e => {
            setValue(e.target.value);
        }
    };

    return [value, bind, reset];
}

Typescipt playground

关于reactjs - 如何在 React with Typescript 中使用和指定 Generic Hooks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65214132/

相关文章:

javascript - API 请求错误 - 请求的资源上不存在 'Access-Control-Allow-Origin' header

reactjs - 两个组件使用相同的组件

javascript - 使用状态钩子(Hook)时,useState() 中的 react 如何为功能组件检索正确的状态对象和函数?

go - 最重要的测试用例

javascript - 如何使用整行作为切换而不是仅使用小的复选框来切换 office-ui-fabric detailslist 行选择

Angular - 缓存 http 响应的最佳方式

reactjs - 如何在组件之外获取RTK查询数据?

javascript - 使用 React Redux 从字符串值调用变量

javascript - ReactJS:使用扩展元素来更新状态

reactjs - 如何更改 react 导航中的后退按钮路线