React的TS开发踩坑指南
大约 1 分钟约 338 字...
创建 react-ts 项目
npx create-react-app my-app --template typescript
npm create vite@latest my-vue-app -- --template react-ts
React
函数式组件props类型定义
interface PropsType {
title: string | JSX.Element,
sideImage: string,
products: any[],
color: string,
}
const Recommendation: React.FC<PropsType> = function ({title,sideImage,products,color}) {
return (
// ...
)
}
Redux ToolKit
获取state的类型
import { configureStore } from '@reduxjs/toolkit'
import rootReducer from './rootReducer'
const store = configureStore({
reducer: rootReducer,
})
export type RootState = ReturnType<typeof store.getState>
returnType
用于获取函数返回值类型,typeof
用于获取函数的类型
获取dispatch的类型
export type AppDispatch = typeof store.dispatch
react-redux
虽然可以将RootState
和AppDispatch
类型导入到每个组件中,但最好创建预先定义好类型的useDispatch
anduseSelector
挂钩以便在您的应用程序中使用。这很重要,原因有几个:
- 对于
useSelector
,它使您无需每次都输入(state: RootState)
- 对于
useDispatch
,默认的Dispatch
类型不包含thunk
或其他中间件
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from '../store'
export const useAppDispatch:() => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
// hoooks/useRedux.ts
react-router
路由配置文件
这个文件应该是tsx
类型,而不是ts
Style-Component
传参时定义类型
interface styledProps {
color: string
}
const Title = styled.span<styledProps>`
color: ${props => props.color};
font-size: 32px;
`