[英]Circular dependency for extracted styles with styled-components
I'm fairly new to styled-components and trying to extract / refactor styles to separate files.我对样式组件相当陌生,并试图提取/重构 styles 以分离文件。 I have problem with circular dependency - probably because of lacks of experience in styled-components good practices.
我有循环依赖的问题 - 可能是因为缺乏样式组件良好实践的经验。 This is the situation:
这是这种情况:
// A.js
import { StyledA } from './styles';
export default () => (
<StyledA>
<SomeOtherComponent />
</StyledA>
);
// B.js
import { StyledA1 } from './styles';
export default () => (
<SomeWrapperComponent>
<StyledA1 />
</SomeWrapperComponent>
);
// styles.js
import styled from 'styled-components';
import A from './A.js';
export const StyledA = styled.div`...`;
export const StyledA1 = styled(A)`...`; // causes dependency circle error
What I'm trying to achieve, is to extend A
component styles and keep it's children components (for file B.js
).我想要实现的是扩展
A
组件 styles 并保留它的子组件(对于文件B.js
)。
export const StyledA1 = styled(StyledA)
doesn't work because I lose component A
structure. export const StyledA1 = styled(StyledA)
不起作用,因为我丢失了组件A
结构。A
in styles.js
causes eslint "dependency-cycle" error because of imports A.js → styles.js → A.js
. A
由于导入A.js → styles.js → A.js
styles.js
eslint“依赖周期”错误。 What should I do to keep HTML structure of extended component and resolve dependency cycle issue?我应该怎么做才能保持扩展组件的 HTML 结构并解决依赖周期问题?
When working with CSS-in-JS (like styled-components
) you usually keep the components generated by style
in the same file .使用 CSS-in-JS(如
styled-components
)时,您通常将style
生成的组件保存在同一个文件中。
So how do you export the className
generated with CSS-in-JS constructor?那么如何导出使用 CSS-in-JS 构造函数生成的
className
呢? By using compound components .通过使用复合组件。
export const StyledA = styled.div`
background: red;
font-size: 20px;
`;
const A = ({ className }) => (
<StyledA className={className}>
<div>Display me always!</div>
</StyledA>
);
// Can use any naming here
A.className = StyledA;
export default A;
Also, when you want to reuse styles , you create file like styles.js
and declare reusable css
blocks:此外,当您想重用 styles时,您可以创建
styles.js
类的文件并声明可重用css
块:
import { css } from 'styled-components';
const border = css`
border: 2px black solid;
`;
export { border };
Full usage:完整用法:
import A from './components/A';
import styled from 'styled-components';
import { border } from './components/styles';
const StyledA = styled(A)`
background-color: palevioletred;
`;
const StyledASelector = styled.div`
${A.className} {
background-color: paleturquoise;
margin: 5px;
${border}
}
`;
const App = () => {
return (
<>
<A />
<StyledA />
<StyledASelector>
<A />
</StyledASelector>
</>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.