嵌套时,条件样式组件会影响所有实例
Conditional styled components effect all instances when nested
如果我在主要组件上使用道具条件,它将按实例工作。
例如,如果我有:
const Div = styled.div<Props>`
${(props) => {
return css`
${props.test && "border: 5px solid red;"};
`;
}}
`;
只有具有 test
属性的组件才会有这个丑陋的边框 :)
但是如果我在嵌套的 css 规则上使用相同的条件:
const Div = styled.div<Props>`
${(props) => {
return css`
.tabletScreen & {
${props.test && "border: 5px solid red;"};
}
`;
}}
`;
如果其中一个组件具有此 test
属性,则此组件的所有实例都将具有此丑陋的边框。
检查它时,我发现组件的所有实例都生成了相同的 class,所以这个:
.tabletScreen .sc-jcFjpl {
border: 5px solid red;
}
对所有实例实施。
但在第一种情况下(当条件未嵌套时)具有 test
属性的组件将获得另一个 class,因此它不会覆盖其他组件。
我该如何解决这个问题?
import React from "react";
import { render } from "react-dom";
import styled, { css } from "styled-components";
import Wrapper from "./Wrapper";
import Title from "./Title";
// Render these styled components like normal react components.
// They will pass on all props and work
// like normal react components – except they're styled!
const Div = styled.div`
${(props) => {
return css`
.tabletScreen {
border: ${props.test && '5px solid red'};
}
`;
}}
`;
const App = () => (
<Wrapper>
<Div test>
Without Test
<div className="tabletScreen">TabletScreen</div>
</Div>
</Wrapper>
);
render(<App />, document.getElementById("root"));
使用 && 而不是 &,它的范围将限定为组件的该样式实例。单符号指的是“静态组件class”。
更多信息在这里:https://styled-components.com/docs/basics#pseudoelements-pseudoselectors-and-nesting
如果我在主要组件上使用道具条件,它将按实例工作。
例如,如果我有:
const Div = styled.div<Props>`
${(props) => {
return css`
${props.test && "border: 5px solid red;"};
`;
}}
`;
只有具有 test
属性的组件才会有这个丑陋的边框 :)
但是如果我在嵌套的 css 规则上使用相同的条件:
const Div = styled.div<Props>`
${(props) => {
return css`
.tabletScreen & {
${props.test && "border: 5px solid red;"};
}
`;
}}
`;
如果其中一个组件具有此 test
属性,则此组件的所有实例都将具有此丑陋的边框。
检查它时,我发现组件的所有实例都生成了相同的 class,所以这个:
.tabletScreen .sc-jcFjpl {
border: 5px solid red;
}
对所有实例实施。
但在第一种情况下(当条件未嵌套时)具有 test
属性的组件将获得另一个 class,因此它不会覆盖其他组件。
我该如何解决这个问题?
import React from "react";
import { render } from "react-dom";
import styled, { css } from "styled-components";
import Wrapper from "./Wrapper";
import Title from "./Title";
// Render these styled components like normal react components.
// They will pass on all props and work
// like normal react components – except they're styled!
const Div = styled.div`
${(props) => {
return css`
.tabletScreen {
border: ${props.test && '5px solid red'};
}
`;
}}
`;
const App = () => (
<Wrapper>
<Div test>
Without Test
<div className="tabletScreen">TabletScreen</div>
</Div>
</Wrapper>
);
render(<App />, document.getElementById("root"));
使用 && 而不是 &,它的范围将限定为组件的该样式实例。单符号指的是“静态组件class”。
更多信息在这里:https://styled-components.com/docs/basics#pseudoelements-pseudoselectors-and-nesting