React 中使用的类型
React 的声明文件定义了名为 React 的命名空间,所以在使用 React 中声明的类型时,都是需要使用 React. 来引用的。
- 所有泛型类型中的
P均指代传递给组件的props的类型,通常根据需要自行使用接口定义,默认为{}。 - 所有泛型类型中的
S均指代组件自身的states的类型,通常也需要使用接口自行定义,默认为{}。 Component<P, S>,组件基类。PureComponent<P, S>,纯组件类。FunctionComponent<P>,函数式组件类,可简写为React.FC<P>。ReactNode,React 组件实例。RefObject<T>,ref引用对象。MutableRefObject<T>,可变ref引用对象。Context<T>,上下文对象。Provider<T>,上下文供应器对象。Consumer<T>,上下文消费者对象。NamedExoticComponent<P>,Memoized 对象。SetStateAction<S>,setState()函数对象Dispatch<A>,dispatch函数对象。Reducer<S, A>,Reducer 对象,其中A为 Action。EffectCallback,副作用函数类型。
常用的函数的声明格式如下,在调用时一般需要指定函数的泛型参数,以返回指定类型的内容。
createContext<T>(defaultValue: T),返回Context<T>类型值。createRef<T>(),返回RefObject<T>类型值。useContext<T>(context: Context<T>),返回T类型值。useState<S>(initial: S | (() => S)),返回[S, Dispatch<SetStateAction<S>>]类型值。useReducer<R, I>(reducer: R, initial: I),返回[ReducerState<R>, Dispatch<ReducerAction<R>>]类型值。useRef<T>(initial: T),返回MutableRefObject<T>类型值。useEffect(effect: EffectCallback, deps?: DependencyList),返回void。useMemo<T>(factory: () => T, deps: DependencyList | undefined),返回T类型值。
这里给出一个简单的函数式组件的编写示例。
interface CounterProps {
user: string;
}
const Counter: React.FC<CounterProps> = (props: CounterProps) => {
const [count, setCount]: [count: number, setCount: Dispatch<SetStateAction<number>>] = useState<number>(0);
return (
<div>
<h1>Hello, {props.user}.</h1>
<div>Current count: {count}.</div>
<input type="button" onClick={() => setCount(count + 1)} />
</div>
);
};