【问题标题】:How to style child components in react styled-components如何在反应样式组件中设置子组件的样式
【发布时间】:2018-04-04 13:16:00
【问题描述】:

我正在尝试设置样式组件的子组件的样式,但它会将 css 发送给父组件而不是子组件/这是我的代码,

export const Card = styled.div`
  position: relative;
  ${props => props.horizontal && `
  ${CardImage}{
     max-height: 60%;
     overflow: hidden;
  }`}
`
export const CardImage = styled.div`
    position: relative;
`

编辑:当我在渲染之前添加一个条件时它不起作用

【问题讨论】:

    标签: javascript reactjs styled-components


    【解决方案1】:

    您快到了,您只是在代码中缺少$,您需要将 CardImage 移到 Card 组件上方:

    export const CardImage = styled.div`
        position: relative;
    `
    
    export const Card = styled.div`
        position: relative;
        ${CardImage}{
            max-height: 60%;
            overflow: hidden;
        }
    `
    

    编辑(2018 年 4 月 4 日):

    如果你想像你一样在整个块周围添加一个条件,你需要从样式组件中导入 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;
            }
        `}
    `
    

    【讨论】:

    • 感谢您的回答,但是当我尝试在样式之前添加条件时,它不起作用。看看编辑
    • @Marvin 您需要在 Card 之前声明 CardImage 就像在我的示例中一样,我还针对您的新情况更新了示例
    • @CubedEye 如果您想使用传递给 CardImage 的道具从 Card 设置 CardImage 的样式怎么办?在 Card 容器中实例化时,您如何访问 CardImage 正在接收的道具?
    • @CubedEye:如果我想把孩子传给CardImage怎么办?做<CardImage>Some Text</CardImage> 不起作用。在带有 React 的 TypeScript 中使用此模式时,我收到错误“没有重载匹配此调用”。
    【解决方案2】:
    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>
      }
    }
    

    它应该适合你吗?

    【讨论】:

    • 我不想将卡片和卡片图像加入到同一个组件中。还有其他方法吗?
    • 您也可以将它们分成不同的组件。我已经编辑了我的答案 - 这就是你的意思吗?
    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多