在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
We are going to start refactoring our There are three ways to type a component, inline, alias, and as a function expression. The inline typing adds a bit of noise to our code and can make it difficult to parse right out of the gate. To fix this, we use a type alias that reads a little bit nicer. To add in a function expression, which we get from the React Types that we downloaded, we can declare this variable to have a type of
JS: import * as React from "react"; import cx from "clsx"; import { scope } from "../lib/utils"; function CountDisplay({ count, className }) { let countString = String(Math.max(Math.min(count, 999), -99)); return ( <div className={cx(scope("count-display"), className)}>{countString}</div> ); } export { CountDisplay };
TS: import * as React from "react"; import cx from "clsx"; import { scope } from "../lib/utils"; function CountDisplay({ count, className }: CountDisplayProps) { let countString = String(Math.max(Math.min(count, 999), -99)); return ( <div className={cx(scope("count-display"), className)}>{countString}</div> ); } export { CountDisplay }; interface CountDisplayProps { count: number; className?: string; }
Or: For function component: TS: import * as React from "react"; import cx from "clsx"; import { scope } from "../lib/utils"; const CountDisplay: React.FunctionComponent<CountDisplayProps> = ({ count, className, }) => { let countString = String(Math.max(Math.min(count, 999), -99)); return ( <div className={cx(scope("count-display"), className)}>{countString}</div> ); };
or a Shorter way: const CountDisplay: React.FC<CountDisplayProps> = ({ count, className, }) => { let countString = String(Math.max(Math.min(count, 999), -99)); return ( <div className={cx(scope("count-display"), className)}>{countString}</div> ); };
VoidFunctionComponent`. const CountDisplay: React.VFC<CountDisplayProps> = ({ count, className, }) => { let countString = String(Math.max(Math.min(count, 999), -99)); return ( <div className={cx(scope("count-display"), className)}>{countString}</div> ); };
Read more TypeScript + React: Why I don't use React.FC |
请发表评论