[英]Destructuring props in the function parameters using TypeScript
I'm trying to my component library to use TypeScript and am attempting to convert a stateless functional component in React from ES6/JavaScript to TypeScript. 我正在尝试使用TypeScript的组件库,并尝试将React中的无状态功能组件从ES6 / JavaScript转换为TypeScript。 I am wondering how I can avoid duplicating myself while still being able to deconstruct props outside the function while passing it parameters.
我想知道如何在传递函数参数的同时仍然能够在函数外部解构props的同时避免重复自己。
My component currently looks like this: 我的组件当前如下所示:
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
};
How would I go about refactoring this into TypeScript? 我将如何将其重构为TypeScript?
type Color = "warning" | 'info'| 'success' | 'danger'
interface IProps {
color: Color
}
const AlertIcon = ({ className, color, ...props }: IProps) => { ... }
now when you use AlertIcon
the color
prop must be of type Color
现在,当您使用
AlertIcon
, color
道具必须为Color
类型
to account for passing HTML attributes, like className
you can do this: 要考虑传递HTML属性(例如
className
您可以执行以下操作:
interface IProps extends HTMLAttributes<HTMLElement> { ... }
where HTMLElement
is your type of element. 其中
HTMLElement
是您的元素类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.