我正在尝试在我的组件库中使用 TypeScript,并尝试将 React 中的无状态功能组件从 ES6/JavaScript 转换为 TypeScript。我想知道如何避免重复自己,同时仍然能够在传递参数时解构函数外部的 props。
我的组件目前如下所示:
const allowedColors = {
warning: "fa fa-exclamation",
info: "fa fa-info",
success: "fa fa-check",
danger: "fa fa-minus-circle"
};
const AlertIcon = ({ className, color, ...props }) => (
<FontAwesomeIcon
{...props}
iconClassName={allowedColors[color]}
className={classNames(`alert-icon-${color}`, className)}
aria-hidden="true"
data-ut="alert-icon"
/>
);
AlertIcon.propTypes = {
className: PropTypes.string,
color: PropTypes.oneOf(Object.keys(allowedColors)).isRequired
};
我该如何将其重构为 TypeScript?
type Color = "warning" | 'info'| 'success' | 'danger'
interface IProps {
color: Color
}
const AlertIcon = ({ className, color, ...props }: IProps) => { ... }
现在当你使用AlertIcon
the color
prop 必须是类型Color
考虑传递 HTML 属性,例如className
你可以这样做:
interface IProps extends HTMLAttributes<HTMLElement> { ... }
where HTMLElement
是你的元素类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)