带有样式组件的 TypeScript [英] TypeScript with styled-components
问题描述
这里是 TypeScript 新手.我有一个使用 styled-components
的以下组件,我想将其转换为 TypeScript
.
TypeScript newbie here. I have a below component using styled-components
that I would like to convert to TypeScript
.
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
const propTypes = {
name: PropTypes.string.isRequired // https://material.io/tools/icons/?style=baseline
}
const Icon = styled(({name, className, ...props}) => <i className={`material-icons ${className}`} {...props}>{name}</i>)`
font-size: ${props => props.theme.sizeLarger};
`
Icon.propTypes = propTypes
export default Icon
我知道我可以用 interface
interface Props {
name: string
}
然而,TypeScript 抱怨我没有声明 className
.问题是,我希望使用 interface
作为开发人员可以提供的道具的一种规范,而不必声明像 className
或 这样的道具主题
由诸如 styled-components
之类的库注入.
However, TypeScript complains that I leave className
undeclared. The thing is, I would ideally like to use the interface
as a sort of spec for props that a developer can provide, without having to declare props like className
or theme
which are injected by libraries like styled-components
.
如何正确地将此组件转换为 TypeScript?
How do I properly convert this component to TypeScript?
推荐答案
import React from "react";
import styled from "styled-components";
interface Props {
name: string;
className?: string;
}
const NonStyledIcon: React.SFC<Props> = ({ name, className, ...props }) => (
<i className={`material-icons ${className}`} {...props}>
{name}
</i>
);
const Icon = styled(NonStyledIcon)`
font-size: ${props => props.theme.sizeLarger};
`;
export default Icon;
根据 styled-components TypeScript 文档:当定义一个组件,您需要在 Props 界面中将 className 标记为可选
As per the styled-components TypeScript docs: when defining a component you will need to mark className as optional in your Props interface
这篇关于带有样式组件的 TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!