React TypeScript中如何为TextArea组件正确声明props类型
为自定义TextArea组件配置正确TypeScript类型的方法
直接将TextareaHTMLAttributes后的<any>替换为HTMLTextAreaElement即可,无需手动逐个声明所有props属性,TypeScript会自动继承原生textarea标签的所有合法属性类型。
修正后的完整代码
import { TextareaHTMLAttributes} from 'react' import styled from 'styled-components' const TextAreaElement = styled.textarea` border-radius: 40px; border: none; background: white; ` const TextArea = (props: TextareaHTMLAttributes<HTMLTextAreaElement>) => { return <TextAreaElement {...props} /> }
类型说明
TextareaHTMLAttributes是React内置的原生textarea属性类型定义,泛型参数要求传入对应HTML元素的实例类型。传入HTMLTextAreaElement后,TypeScript会自动推导placeholder、value、onChange、disabled等所有原生属性、事件的正确类型,传入非法属性时会直接触发类型报错。- 如果需要新增自定义组件属性,直接通过交叉类型扩展原有类型即可,不需要重复声明原生属性:
type CustomTextAreaProps = TextareaHTMLAttributes<HTMLTextAreaElement> & { showWordCount?: boolean wrapperClassName?: string } const TextArea = (props: CustomTextAreaProps) => { return <TextAreaElement {...props} /> }
- 如果需要支持ref透传,配合
forwardRef使用即可,同样不需要手动罗列原生属性:
import { forwardRef, TextareaHTMLAttributes } from 'react' const TextArea = forwardRef<HTMLTextAreaElement, TextareaHTMLAttributes<HTMLTextAreaElement>>( (props, ref) => <TextAreaElement ref={ref} {...props} /> )
内容的提问来源于stack exchange,提问作者peter flanagan
相关产品推荐
相关产品推荐

