在组件中引用另一个组件时遇到问题
Having trouble referring to another component within a component
我正在尝试根据它在页面上显示的顺序更改 div 上的浮动 – 例如奇数向左浮动,偶数向右浮动——但是当我在现有组件中引用该组件时没有任何反应。
这是使用 gatsbyjs 和样式组件在 reactjs 中构建的。
如果我做类似的事情,我可以让 &:nth-of-type(even) 工作:
${Image}:before {
background: red;
}
但是没有':before'什么也不会发生。至少我无话可说。
更具体地说——也许有更好的方法来做到这一点——我正在尝试做的是,即使是 BlogList 中的文章,图像也能正确浮动。奇怪的文章向左浮动。我已经简化了我的代码,因为你们都不需要看到背景颜色等。
const Wrapper = style.article`
&:nth-of-type(even) {
${Image} {
float: right;
}
}
`;
const Image = style.div`
float: left;
`;
const Info = style.div`
float: right;
`;
const BlogList = ({ title, cover, excerpt }) => (
<Wrapper>
<Image>
<Img fluid={cover} />
</Image>
<Info>
<h2>{title}</h2>
<p>{excerpt}</p>
</Info>
</Wrapper>
);
理论上,按照我的阅读方式,我应该让 in 事件向左浮动。但我不是。我在这里错过了什么?
如果您在 Wrapper
中引用 Image
和 Info
,则必须在 Wrapper
之前声明它们。
const Image = style.div`
float: left;
`;
const Info = style.div`
float: right;
`;
const Wrapper = styled.article`
${Info} { ... }
${Image} { ... }
`
否则,styled-component
不知道其他组件是什么。我很惊讶它没有抛出错误。
我已经弄明白了。原来我指的是倒过来的组件。虽然我确信有一个更清晰的答案,但以下是对我有用的答案:
const Wrapper = styled.article`
`;
const Image = styled.div`
${Wrapper}:nth-of-type(odd) & {
float: left;
}
${Wrapper}:nth-of-type(even) & {
float: right;
}
`;
const Info = styled.div`
${Wrapper}:nth-of-type(odd) & {
float: right;
}
${Wrapper}:nth-of-type(even) & {
float: left;
}
`;
我正在尝试根据它在页面上显示的顺序更改 div 上的浮动 – 例如奇数向左浮动,偶数向右浮动——但是当我在现有组件中引用该组件时没有任何反应。
这是使用 gatsbyjs 和样式组件在 reactjs 中构建的。
如果我做类似的事情,我可以让 &:nth-of-type(even) 工作:
${Image}:before {
background: red;
}
但是没有':before'什么也不会发生。至少我无话可说。
更具体地说——也许有更好的方法来做到这一点——我正在尝试做的是,即使是 BlogList 中的文章,图像也能正确浮动。奇怪的文章向左浮动。我已经简化了我的代码,因为你们都不需要看到背景颜色等。
const Wrapper = style.article`
&:nth-of-type(even) {
${Image} {
float: right;
}
}
`;
const Image = style.div`
float: left;
`;
const Info = style.div`
float: right;
`;
const BlogList = ({ title, cover, excerpt }) => (
<Wrapper>
<Image>
<Img fluid={cover} />
</Image>
<Info>
<h2>{title}</h2>
<p>{excerpt}</p>
</Info>
</Wrapper>
);
理论上,按照我的阅读方式,我应该让 in 事件向左浮动。但我不是。我在这里错过了什么?
如果您在 Wrapper
中引用 Image
和 Info
,则必须在 Wrapper
之前声明它们。
const Image = style.div`
float: left;
`;
const Info = style.div`
float: right;
`;
const Wrapper = styled.article`
${Info} { ... }
${Image} { ... }
`
否则,styled-component
不知道其他组件是什么。我很惊讶它没有抛出错误。
我已经弄明白了。原来我指的是倒过来的组件。虽然我确信有一个更清晰的答案,但以下是对我有用的答案:
const Wrapper = styled.article`
`;
const Image = styled.div`
${Wrapper}:nth-of-type(odd) & {
float: left;
}
${Wrapper}:nth-of-type(even) & {
float: right;
}
`;
const Info = styled.div`
${Wrapper}:nth-of-type(odd) & {
float: right;
}
${Wrapper}:nth-of-type(even) & {
float: left;
}
`;