typescript 与类型脚本类型进行React

hxzsmxv2  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(137)

如果我使用react with typescript(tsx),就像这样:

import { Dispatch, SetStateAction } from "react";

export function MyCounter({ count, onCountChange }: { count: number; onCountChange: Dispatch<SetStateAction<number>> }) {
    return (
        <>
            <p>Count: {count}</p>
            <button onClick={() => onCountChange(count + 1)}>Increment</button>
            <button onClick={() => onCountChange(count - 1)}>Decrement</button>
        </>
    );
}

有没有办法简化 prop 的类型?或者有一个最好的做法是如何做到这一点?
有一个像这样的自定义类型是个好主意吗?:

import { Dispatch, SetStateAction } from "react";

export type MyCounterProps = {
    count: number;
    onCountChange: Dispatch<SetStateAction<number>>;
};

export function MyCounter({ count, onCountChange }: MyCounterProps) {
    return (
        <>
            <p>Count: {count}</p>
            <button onClick={() => onCountChange(count + 1)}>Increment</button>
            <button onClick={() => onCountChange(count - 1)}>Decrement</button>
        </>
    );
}
w6lpcovy

w6lpcovy1#

我通常是这样做的:

import {FC} from "react"
//Define a interface for this component
interface IProps {
    count: number;
    onCountChange: Dispatch<SetStateAction<number>>;
};
//Assign it as FunctionalComponent type with IProps interface
export function MyCounter:FC<IProps>({ count, onCountChange }) {

定义类型或接口属性,然后将其分配给功能组件本身,这样会更简洁。

相关问题