【发布时间】:2020-09-10 17:21:57
【问题描述】:
我对如何将 .attrs() 函数与 TypeScript 一起使用有点困惑。假设我有以下内容:
BottleBar.tsx:
interface IBottleComponentProps {
fill?: boolean
}
const BottleComponent = styled.div.attrs<IBottleComponentProps>(({fill}) => ({
style: {
backgroundImage: `url("./media/images/${fill ? 'Bottle-Filled.png' : 'Bottle-Empty.png'")`
}
}))<IBottleComponentProps`
width: 20px;
height: 20px;
`;
export default function BottleBar() {
return (
<Wrapper>
<BottleComponent />
<BottleComponent fill />
</Wrapper>
)
}
现在,上面的代码有效,但我不确定为什么在开头和结尾都需要两次 IBottleComponentProps - 如果没有它,我会得到以下信息:
Type '{ fill: boolean; }' is not assignable to type 'IntrinsicAttributes & Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "slot" | ... 253 more ... | "onTransitionEndCapture"> & { ...; }, "slot" | ... 254 more ... | "onTransitionEndCapture"> & Partial<...>, "slot" | ... 254 more ... | "onTransitionEndCapture"> & { ...; } & { ...; }'.
另外,在第一个代码示例中,我得到了一个浏览器日志;
index.js:1 Warning: Received `true` for a non-boolean attribute `fill`.
老实说,这很令人困惑,并且 Styled-Components 文档在这方面不是很清楚。非常感谢您朝着正确的方向前进。
【问题讨论】:
标签: reactjs typescript styled-components