如果我使用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>
</>
);
}
1条答案
按热度按时间w6lpcovy1#
我通常是这样做的:
定义类型或接口属性,然后将其分配给功能组件本身,这样会更简洁。