在过去的8个月里,我一直在一个大型项目中使用样式组件(目前使用的是v4.3.2),这是我第一次遇到这个问题,我不知道该如何修复,也不知道为什么会发生这个问题。以下是复制此问题的CodeSandbox的链接:
https://codesandbox.io/embed/stoic-pine-5iixv
当我去给一个预先存在的样式组件添加新功能时,这种情况就开始发生了。看起来包含withTheme HOC是最初导致错误发生的原因。以下是我在开始添加新功能之前的组件:
import styled from "styled-components";
import { Flex } from "@rebass/grid";
const InlineTabList = styled(Flex)`
border: 1px solid ${p => p.theme.grey};
border-radius: ${p => p.theme.borderRadius};
overflow: hidden;
`;
export default InlineTabList;下面是一个导致错误的非常基本的例子:
import React from "react";
import styled, { withTheme } from "styled-components";
import { Flex } from "@rebass/grid";
const Root = styled(Flex)`
border: 1px solid ${p => p.theme.grey};
border-radius: ${p => p.theme.borderRadius};
overflow: hidden;
`;
const InlineTabList = ({ children }) => {
return <Root>{children}</Root>;
};
export default withTheme(InlineTabList);我还注意到,如果在tab.js组件中删除对InlineTabList或TabList的引用,它也会修复错误,但这是引用文档中列出的其他组件的首选方式:https://www.styled-components.com/docs/advanced#referring-to-other-components。
任何帮助都将不胜感激。
发布于 2019-09-02 14:37:40
样式化组件中的组件选择器应该只与样式化组件一起使用,而您在这里将其与React组件一起使用:
${InlineTabList} & {您可以通过从InlineTabList而不是InlineTabList导入Root样式的组件来测试它,它不会给出错误。你也可以用styled()方法包装整个东西(然后withTheme就变得多余了)。
实际上,您包含的链接后面就有答案:https://www.styled-components.com/docs/advanced#caveat
此外,我不确定这是否是因为您的最小示例,但是为什么您要在每个包装器组件中使用withTheme?样式化组件已经自动传递了主题道具,而无需您执行此操作。
https://stackoverflow.com/questions/57737693
复制相似问题