javascript - ¿Cómo agrego tipo a las funciones onChange y onClick en react con typescript?
He definido un componente
type Props = {
label:string,
autoFocus:boolean,
onClick:(e: React.ClickEvent<HTMLInputElement>) => void,
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
}
const Input = ({ handleChange, label, autoFocus, handleClick }:Props) => (
<TextField
onChange={handleChange}
required
label={label}
autoFocus={autoFocus}
onClick={handleClick}
}
/>
);
Estoy convirtiendo mis componentes de React a TypeScript por primera vez, estoy un poco confundido sobre qué tipo debería escribir para las funciones que estoy recibiendo en las props. Sobre la iniciación del tipo Props, entiendo que string y boolean, pero ¿cómo debería manejar alguien la tipificación de funciones de eventos?
Respuesta #1
Puedes definir handleClick como React.MouseEventHandler<HTMLInputElement>:
import { TextField } from "@material-ui/core";
import React from "react";
type Props = {
label: string;
autoFocus?: boolean;
handleClick?: React.MouseEventHandler<HTMLInputElement>;
handleChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
};
const Input = ({ handleChange, label, autoFocus, handleClick }: Props) => (
<TextField
onChange={handleChange}
required
label={label}
autoFocus={autoFocus}
onClick={handleClick}
/>
);
export default function App() {
return <Input label="CustomInput" />;
}
Respuesta #2
Como queremos usar MUI para soportar los tipos y ser una fuente única de verdad, sugeriría inferir los tipos del propio Material UI, en lugar de crear tipos separados.
import { TextField, TextFieldProps } from '@mui/material';
type Props = {
handleChange: TextFieldProps['onChange'];
handleClick: TextFieldProps['onClick'];
label: TextFieldProps['label'];
autoFocus: TextFieldProps['autoFocus'];
};
const Input = ({ handleChange, label, autoFocus, handleClick }: Props) => (
<TextField
onChange={handleChange}
required
label={label}
autoFocus={autoFocus}
onClick={handleClick}
/>
);