React meets Typescript

React meets Typescript

React and Typescript are used in combination, and you always write by referring to the vscode prompt type every day, to record it, and continue to add it later.

Define component props type

Import React from 'REACT' ; //type type AppProps = { name : string ; children: React.ReactNode; status: 'success' | 'error' ; }; //interface interface AppProps { name : string ; children: React.ReactNode; status: 'success' | 'error' ; } const App = ( {name, children, status }: AppProps ) => ( < div > < span > {name} </span > < span > {status} </span > {children} </div > ); export default App; Copy code

JSX.Element and React.ReactNode?

type AppProps = { children : JSX.Element | React.ReactNode; }; const App = ( {children }: AppProps ) => { return <> children </> ; }; const Index = () => { return ( //When children is JSX.Element, children can only be jsx element tags, not strings, for example: <App>text</App> < App > < span > asda </span > </App > //When children is React.ReactNode, children can be any element < App >A description </App > ); }; export default Index; //React.ReactNode is a component of the return of all possible types of collections copy the code

Define Function Components

Import React from 'REACT' ; type AppProps = { name : string ; }; //React.FC defines the props type, there will be a default children property const App: React.FC<AppProps> = ( {name, children} ) => < div > {name} </div > ; //No need for children to use the parameter type method or React.VoidFunctionComponent<AppProps> const App = ( {name }: AppProps ) => < div > (name) </div > ; export default App; copy code

useState and useRef

const App = () => { //The default is undefined const [name, setName] = useState< string | undefined >(); //ref const divRef = useRef<HTMLDivElement>( null ); return < div ref = {divRef} > {name} </div > ; }; Copy code

useImperativeHandle

//The method that the parent component calls the child component. The first type of forwardRef is the attribute mounted on ref, and the second type is the props type. type Props = { name : string }; type Ref = { sayHello : () => void ; }; const Child = forwardRef<Ref, Props>( ( {name }, ref ) => { useImperativeHandle(ref, () => ({ sayHello : () => console .log( 'hello' ), })); return < div > {name} </div > ; }); const Parent = () => { const childRef = useRef<Ref>( null ); return ( < div > < Child ref = {childRef} name = "child" > </Child > </div > ); }; Copy code

useContext

Import React from 'REACT' ; interface AppContextInterface { name : string ; } //null! means that the value is not null, there must be const AppCtx = React.createContext<AppContextInterface>( null !); const sampleAppContext: AppContextInterface = { name : 'Typescript React App' , }; export const App = () => ( < AppCtx.Provider value = {sampleAppContext} > ... </AppCtx.Provider > ); export const PostInfo = () => { const appContext = React.useContext(AppCtx); return < div > Name: {appContext.name} </div > ; }; Copy code

createPortal

Import React, {useEffect, useRef} from 'REACT' ; Import {createPortal} from 'DOM-REACT' ; const modalRoot = document .body; const Modal: React.FC<{}> = ( {children} ) => { const el = useRef( document .createElement( 'div' )); useEffect( () => { const current = el.current; modalRoot.appendChild(current); return () => void modalRoot.removeChild(current); }, []); return createPortal(children, el.current); }; Export default Modal; //createPortal assembly may be rendered to the specified elements, such as Modal antd the duplicated code

ts some tips

//! Means that type inference excludes undefined and null document .getElementById( 'root' )!.parentNode; //Type combination use type AnimalType = { name : string ; }; type DogType = { age : number ; }; const Dog = ( {name, age }: AnimalType & DogType ) => ( < div > {name} {age} </div > ); //Implement interface AnimalInterface through interface inheritance { name : string ; } interface DogInterface extends AnimalInterface { age : string ; } const Dog = ( {name, age }: DogInterface ) => ( < div > {name} {age} </div > ); Copy code
//function type defined type FunctionType = ( X: Number , Y: Number ) => Number ; type FunctionType1 = ( X: Number , Y: Number ) => Promise < Number >; duplicated code
//Function overloading //Overloading: the method name is the same, the parameter type is different, and the return value type can also be different function renderTable ( data: {name: string ; age: number } ): number ; function renderTable ( data: string ): string ; function renderTable ( data ): any { //bala bala bala.... } renderTable({ name : '1' , age : 1 }); renderTable( 'hello' ); Copy code
//typeof gets the type of the variable without redeclaring const App = () => { const [state, setState] = React.useState({ name : ' ' , age : 2 , }); const method = ( obj: Partial< typeof state> ) => { setState(obj); }; } //Partial <typeof state> -> {name:? String; age: number;} copy the code
//Omit removes an attribute from a type type User = { id : string ; name: string ; email: string ; }; type UserWithoutEmail = Omit<User, 'email' >; Omit<User, 'email' > is equivalent to type UserWithoutEmail = { id : string ; name: string ; }; Copy code

Imitate writing a useSafeState hooks

//The central idea is to use a variable to mark whether the component is uninstalled. If it is uninstalled, it will not setState, so that it will not cause unexpected situations such as memory leaks. import {useState, useEffect, useRef, Dispatch, SetStateAction} from 'REACT' ; function useSafeState < S >( initialState: S | (() => S) ): [ S , Dispatch < SetStateAction < S >>] ; function useSafeState < S = undefined >(): [ S | undefined , Dispatch < SetStateAction < S | undefined >>,] ; function useSafeState < T >( initialValue?: T ) { const [state, setState] = useState(initialValue); const isUnMounted = useRef( false ); useEffect( () => { return () => { isUnMounted.current = true ; }; }, []); const setSafeState = ( value: T ) => { if (!isUnMounted.current) { setState(value); } }; return [state, setSafeState] as const ; } export default useSafeState; Copy code