复用React内置类型解决按钮组件Props类型不匹配问题
这个问题我之前也碰到过,手动枚举"button" | "reset" | "submit"不仅麻烦,还容易和React内置类型不同步,复用官方提供的类型是最优雅的解决方式,下面给出两种常用的实现方案:
方案一:单独提取button type的内置类型
如果你只需要复用button的type类型,不需要继承其他原生props,可以直接从React的ButtonHTMLAttributes中提取对应的类型:
import React from 'react'; // 从React内置的button属性类型中提取type的类型定义 type ButtonType = React.ButtonHTMLAttributes<HTMLButtonElement>['type']; // 定义你的组件Props,复用提取的类型 interface MyCustomButtonProps { buttonType?: ButtonType; // 这里可以添加你的其他自定义Props label?: string; } const MyCustomButton: React.FC<MyCustomButtonProps> = ({ buttonType = 'button', label, children }) => { return ( <button type={buttonType}> {label || children} </button> ); };
这样buttonType的类型就和React内置的button元素type属性完全一致了,既避免了手动枚举,也不会出现TypeScript类型不匹配的报错。
方案二:直接扩展button的原生属性类型
如果你的组件需要支持button元素的所有原生Props(比如disabled、onClick等),同时添加自定义属性,可以直接扩展ButtonHTMLAttributes:
import React from 'react'; // 扩展React内置的button属性类型,添加自定义Props interface MyCustomButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { // 自定义属性示例 customClass?: string; } const MyCustomButton: React.FC<MyCustomButtonProps> = ({ type = 'button', customClass, children, ...restProps }) => { return ( <button type={type} className={customClass} {...restProps} > {children} </button> ); };
这种方式下,组件的type属性直接继承了React内置的类型定义,同时还能支持所有button原生属性,非常适合封装通用按钮组件的场景。
内容的提问来源于stack exchange,提问作者CaribouCode
相关产品推荐
相关产品推荐

