Actualmente estoy migrando una aplicación React a TypeScript. Hasta ahora, esto funciona bastante bien, pero tengo un problema con los tipos de retorno de mis funciones de render , específicamente en mis componentes funcionales.
Siempre he usado JSX.Element como el tipo de retorno, ahora esto ya no funciona si un componente decide no mostrar nada, es decir, devuelve null , ya que null no es un valor válido para JSX.Element . Este fue el comienzo de mi viaje. Busqué en la web y descubrí que debería usar ReactNode en su lugar, que incluye null y algunas otras cosas que pueden suceder.
Sin embargo, al crear un componente funcional, TypeScript se queja del tipo ReactNode . Nuevamente, después de algunas búsquedas, encontré que para los componentes funcionales debería usar ReactElement en su lugar. Sin embargo, si lo hago, el problema de compatibilidad desaparecerá, pero ahora TypeScript nuevamente se queja de que null no es un valor válido.
Para abreviar una larga historia, tengo tres preguntas:
JSX.Element , ReactNode y ReactElement ?render de los componentes de clase devuelven ReactNode , pero los componentes funcionales devuelven ReactElement ?null ?¿Cuál es la diferencia entre JSX.Element, ReactNode y ReactElement?
Un ReactElement es un objeto con un tipo y accesorios.
type Key = string | number interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> { type: T; props: P; key: Key | null; }Un ReactNode es un ReactElement, un ReactFragment, una cadena, un número o una matriz de ReactNodes, o nulo, indefinido o booleano:
type ReactText = string | number; type ReactChild = ReactElement | ReactText; interface ReactNodeArray extends Array<ReactNode> {} type ReactFragment = {} | ReactNodeArray; type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;JSX.Element es un ReactElement, con el tipo genérico para accesorios y el tipo es cualquiera. Existe, ya que varias bibliotecas pueden implementar JSX a su manera, por lo tanto, JSX es un espacio de nombres global que luego establece la biblioteca, React lo establece así:
declare global { namespace JSX { interface Element extends React.ReactElement<any, any> { } } }Por ejemplo:
<p> // <- ReactElement = JSX.Element <Custom> // <- ReactElement = JSX.Element {true && "test"} // <- ReactNode </Custom> </p>¿Por qué los métodos de representación de los componentes de clase devuelven ReactNode, pero los componentes de función devuelven ReactElement?
De hecho, devuelven cosas diferentes. Devolución de Component :
render(): ReactNode;Y las funciones son "componentes sin estado":
interface StatelessComponent<P = {}> { (props: P & { children?: ReactNode }, context?: any): ReactElement | null; // ... doesn't matter }En realidad, esto se debe a razones históricas .
¿Cómo resuelvo esto con respecto a nulo?
Escríbalo como ReactElement | null tal como lo hace react. O deje que Typescript infiera el tipo.
https://github.com/typescript-cheatsheets/react#useful-react-prop-type-examples
export declare interface AppProps { children1: JSX.Element; // bad, doesnt account for arrays children2: JSX.Element | JSX.Element[]; // meh, doesn't accept strings children3: React.ReactChildren; // despite the name, not at all an appropriate type; it is a utility children4: React.ReactChild[]; // better, accepts array children children: React.ReactNode; // best, accepts everything (see edge case below) functionChildren: (name: string) => React.ReactNode; // recommended function as a child render prop type style?: React.CSSProperties; // to pass through style props onChange?: React.FormEventHandler<HTMLInputElement>; // form events! the generic parameter is the type of event.target // more info: https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#wrappingmirroring props: Props & React.ComponentPropsWithoutRef<"button">; // to impersonate all the props of a button element and explicitly not forwarding its ref props2: Props & React.ComponentPropsWithRef<MyButtonWithForwardRef>; // to impersonate all the props of MyButtonForwardedRef and explicitly forwarding its ref }