React 中的 TypeScript (TSX) - 常见和高级用法
TypeScript (TS) 通过 TSX(TypeScript 与 JSX 的结合)增强了 React 应用程序,为其提供了强类型支持。以下是在 React 中使用 TypeScript 的一些常见和高级用法。
常见用法
1. 定义组件 Props 和 State 类型
tsx
type AppProps = { message: string; };
type AppState = { count: number; };
class App extends React.Component<AppProps, AppState> {
state: AppState = { count: 0 };
render() { return <div>{this.props.message}</div>; }
}
type AppProps = { message: string; };
type AppState = { count: number; };
class App extends React.Component<AppProps, AppState> {
state: AppState = { count: 0 };
render() { return <div>{this.props.message}</div>; }
}
2. 使用接口定义组件属性
tsx
interface IProps { title: string; }
const HeaderComponent: React.FC<IProps> = ({ title }) => <header>{title}</header>;
interface IProps { title: string; }
const HeaderComponent: React.FC<IProps> = ({ title }) => <header>{title}</header>;
3. 使用泛型
tsx
interface IListProps<T> { items: T[]; renderItem: (item: T) => React.ReactNode; }
function List<T>(props: IListProps<T>) { return <ul>{props.items.map(props.renderItem)}</ul>; }
interface IListProps<T> { items: T[]; renderItem: (item: T) => React.ReactNode; }
function List<T>(props: IListProps<T>) { return <ul>{props.items.map(props.renderItem)}</ul>; }
4. 类型断言
tsx
const myElement = <div>Example</div> as JSX.Element;
const myElement = <div>Example</div> as JSX.Element;
5. 枚举和联合类型
tsx
enum ButtonType { Primary = "primary", Secondary = "secondary" }
interface ButtonProps { type: ButtonType; }
const Button: React.FC<ButtonProps> = ({ type }) => <button className={type}>{type}</button>;
enum ButtonType { Primary = "primary", Secondary = "secondary" }
interface ButtonProps { type: ButtonType; }
const Button: React.FC<ButtonProps> = ({ type }) => <button className={type}>{type}</button>;
6. 高阶组件(HOC)与 TypeScript
tsx
function withLogger<T>(Component: React.ComponentType<T>) {
return (props: T) => { console.log(props); return <Component {...props} />; };
}
function withLogger<T>(Component: React.ComponentType<T>) {
return (props: T) => { console.log(props); return <Component {...props} />; };
}
高级用法
1. 条件类型
tsx
type PropsWithChildren<T> = T extends {} ? T & { children: React.ReactNode } : never;
const ComponentWithChildren: React.FC<PropsWithChildren<{}>> = ({ children }) => <div>{children}</div>;
type PropsWithChildren<T> = T extends {} ? T & { children: React.ReactNode } : never;
const ComponentWithChildren: React.FC<PropsWithChildren<{}>> = ({ children }) => <div>{children}</div>;
2. 映射类型
tsx
type ReadOnly<T> = { readonly [P in keyof T]: T[P] };
interface IUser { name: string; age: number; }
const ReadOnlyUser: React.FC<{ user: ReadOnly<IUser> }> = ({ user }) => <div>{user.name}</div>;
type ReadOnly<T> = { readonly [P in keyof T]: T[P] };
interface IUser { name: string; age: number; }
const ReadOnlyUser: React.FC<{ user: ReadOnly<IUser> }> = ({ user }) => <div>{user.name}</div>;
3. 使用实用工具类型
tsx
interface IFormValues { username: string; password: string; }
const PartialForm: React.FC<{ values: Partial<IFormValues> }> = ({ values }) => <div>{values.username}</div>;
interface IFormValues { username: string; password: string; }
const PartialForm: React.FC<{ values: Partial<IFormValues> }> = ({ values }) => <div>{values.username}</div>;
4. 泛型在高阶组件(HOC)中的应用
tsx
function withDefaults<T extends {}>(Component: React.ComponentType<T>, defaultProps: Partial<T>) {
return (props: T) => <Component {...defaultProps} {...props} />;
}
function withDefaults<T extends {}>(Component: React.ComponentType<T>, defaultProps: Partial<T>) {
return (props: T) => <Component {...defaultProps} {...props} />;
}
5. 带有类型的自定义钩子
tsx
function useCustomHook<T>(initialValue: T): [T, (newValue: T) => void] {
const [value, setValue] = useState<T>(initialValue);
return [value, setValue];
}
function useCustomHook<T>(initialValue: T): [T, (newValue: T) => void] {
const [value, setValue] = useState<T>(initialValue);
return [value, setValue];
}
6. 鉴别联合类型
tsx
interface LoadingState { state: 'loading'; }
interface LoadedState { state: 'loaded'; content: string; }
type ComponentState = LoadingState | LoadedState;
const MyComponent: React.FC<{ state: ComponentState }> = ({ state }) => {
switch (state.state) {
case 'loading': return <div>Loading...</div>;
case 'loaded': return <div>{state.content}</div>;
}
};
interface LoadingState { state: 'loading'; }
interface LoadedState { state: 'loaded'; content: string; }
type ComponentState = LoadingState | LoadedState;
const MyComponent: React.FC<{ state: ComponentState }> = ({ state }) => {
switch (state.state) {
case 'loading': return <div>Loading...</div>;
case 'loaded': return <div>{state.content}</div>;
}
};
这些示例展示了如何在 React 中使用 TypeScript 来创建健壮和可维护的应用程序。