【发布时间】:2021-02-12 04:50:46
【问题描述】:
在 react 的 hoc 包装器中使用样式化组件有两个问题。
- 组件已渲染,但未使用背景颜色。
- ComponentWithAddedColors 不是有效的打字稿。不知道为什么。
谁能帮忙解决这个问题?
interface IProps {
id: string;
left: number;
top: number;
}
export const Node: React.FC<IProps> = ({ id, left, top }) => {
return (
<Container left={left} top={top}>
{id}
</Container>
);
};
function withColors<T>(Component: React.ComponentType<T>) {
const bg = "hotpink";
const ComponentWithAddedColors = styled(Component)`
${bg && `background: ${bg};`}
`;
const result: React.FC<T> = (props) => (
<ComponentWithAddedColors {...props} />
);
return result;
}
const DraggableNode = withColors(Node);
export default DraggableNode;
我制作了一个代码沙箱来说明这个问题: https://codesandbox.io/s/styled-hoc-xgduo?file=/src/Components/Node/Node.tsx
【问题讨论】:
-
这是因为
styled函数只接受样式化组件 - 意思是,由styled创建的组件,就像在 their exampe 中一样。看到这个:codesandbox.io/s/styled-hoc-forked-wjb99?file=/src/Components/… -
@MoshFeu 感谢您的反馈。你知道为什么还会出现打字稿错误吗?
-
@MoshFeu 我刚刚检查了类型定义文件的样式。它确实接受 JSX.IntrinsicElements 作为参数。问题在于文档底部的描述:“但是,将 A 包装在 styled() 工厂中使其符合插值条件 - 只需确保包装的组件通过 className。”
标签: reactjs typescript styled-components