I have an Input
base component and then I want to create a Textarea
extending it.
type InputProps {
name: string;
}
const Input = styled.input.attrs((props) => ({name: props.name, id: props.name})<InputProps>``;
const Textarea = styled(Input).attrs({as: "textarea"})``;
Now when I want to use the Textarea
with an onChange
handler Im getting type conflicts:
const onChange = (e: ChangeEvent<HTMLTextareaElement>) => {};
<Textara name="text" onChange={onChange} />
Produces:
Error: Type '(e: ChangeEvent<HTMLTextAreaElement>) => void' is not assignable to type ChangeEventHandler<HTMLInputElement>'.
How can I solve this problem? Im currently using a variable to to share my CSS between the same components but thats more of a workaround.
Way 01: apply as
directly on Textarea
to have a more precise guess on the type in compile time
const Textarea = styled(Input)``;
// still the input is input element so the guessing of the type will include HTMLInputElement
const onChange = (e: ChangeEvent<HTMLInputElement> & React.ChangeEvent<HTMLTextAreaElement>) => {}
<Textarea as="textarea" name="text" onChange={onChange} />
Way 02: use HTMLElement
to cover all html elements and cast the type inside onChange
const Textarea = styled(Input).attrs({as: "textarea"})``;
const onChange = (e: ChangeEvent<HTMLElement>) => {
const { value } = e.target as HTMLTextAreaElement
console.log(value)
};
<Textarea name="text" onChange={onChange} />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.