[英]How to style child components in react styled-components
I'm trying to style the child component of a styled-component, but it sends the css to the parent instead of the child/ This is my code, 我正在尝试设置样式化组件的子组件的样式,但是它将CSS发送给父组件而不是子组件/这是我的代码,
export const Card = styled.div`
position: relative;
${props => props.horizontal && `
${CardImage}{
max-height: 60%;
overflow: hidden;
}`}
`
export const CardImage = styled.div`
position: relative;
`
EDIT: When I add a condition before rendering that's when it doesn't work 编辑:当我在渲染之前添加条件时,那是行不通的
You're almost there, you're just missing a $
in your code and you'll need to move the CardImage above the Card component: 您快到$
,您的代码中只缺少$
,需要将CardImage移动到Card组件上方:
export const CardImage = styled.div`
position: relative;
`
export const Card = styled.div`
position: relative;
${CardImage}{
max-height: 60%;
overflow: hidden;
}
`
Edit (04/04/2018): 编辑(04/04/2018):
If you want to add a condition around a whole block like you have, you need to import the css
function from styled components and use that: 如果要像周围一样在整个块周围添加条件,则需要从样式化的组件中导入css
函数,并使用该函数:
import styled, {css} from "styled-components";
export const CardImage = styled.div`
position: relative;
`
export const Card = styled.div`
position: relative;
${props => props.horizontal && css` // - Notice the css` here.
${CardImage}{
max-height: 60%;
overflow: hidden;
}
`}
`
const StyledCard = styled.div`
//parent styles goes here
`;
const StyledImage = styled.img`
//image styles
`;
class CardImage extends Component {
render() {
return <StyledImage/>
}
export default class Card extends Component {
render() {
return <StyledCard>
<CardImage/>
</StyledCard>
}
}
Should it work for you? 它应该为您工作吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.