如何在TypeScript中为Emotion React的Input组件添加pointer自定义属性?
解决Emotion React自定义组件属性的TypeScript类型错误
问题场景
用Emotion React创建InputField组件并添加自定义pointer属性后,TypeScript提示pointer不存在于input元素上。尝试扩展React输入属性接口并赋值给组件后,又出现两个错误:styled对象缺少pointer属性,且JSX中InputField元素没有构造或调用签名。
错误原因
直接将扩展后的属性接口赋值给组件变量是错误的——Emotion的styled函数返回的是React组件类型,而非HTML元素的属性接口,两者类型不匹配,导致TypeScript报错。
正确解决方案
步骤1:定义组件Props接口
先创建继承自input原生属性的接口,添加自定义pointer属性:
import styled from '@emotion/styled'; import React from 'react'; interface InputFieldProps extends React.InputHTMLAttributes<HTMLInputElement> { pointer: boolean; }
步骤2:为Styled组件指定Props类型
有两种方式可以给Emotion组件绑定自定义属性类型:
方式一:使用泛型指定Props
const InputField = styled.input<InputFieldProps>(({ pointer, ...rest }) => ({ all: 'unset', width: 200, display: 'inline-flex', alignItems: 'center', // 根据pointer属性设置样式示例 cursor: pointer ? 'pointer' : 'text', // 其他样式代码... }));
方式二:在样式回调参数中指定类型
const InputField = styled('input')(({ pointer, ...rest }: InputFieldProps) => ({ all: 'unset', width: 200, display: 'inline-flex', alignItems: 'center', cursor: pointer ? 'pointer' : 'text', }));
步骤3:正常使用组件
此时在JSX中使用InputField时,TypeScript会正确识别所有原生input属性和自定义pointer属性:
<InputField placeholder={placeholder} pointer={insidePool} readOnly={insidePool} type={type} onChange={onChange} />
内容的提问来源于stack exchange,提问作者sir-haver
相关产品推荐
相关产品推荐

