【问题标题】:How to render pseudo before content dynamically in styled-component如何在样式组件中动态呈现伪内容之前
【发布时间】:2018-03-02 12:24:41
【问题描述】:

我在样式组件中动态呈现伪内容之前遇到了麻烦。

我做错了吗?

我在静态渲染内容之前没有问题,但是当我动态尝试时它不起作用。

反应组件

const Test = (props) => {

    return (
        <Text before={12345}>
            {props.children}
        </Text>
    );

};

样式化组件(不工作)

const Text = styled.span`

    &:before {
        content: ${props => {
            console.log(props.before); // I see '12345' in log.
            return props.before;
            }
    }


`;

样式化组件(这很好用)

const Text = styled.span`

    &:before {
        content: '12345'
    }


`;

【问题讨论】:

  • 不建议将动态内容属性与样式化组件一起使用,因为它会为每个内容创建新类,如果只有几个不同的“内容”你很好,但如果它可以是任何东西你可能表现不佳。

标签: reactjs styled-components


【解决方案1】:

这是因为 content 值必须在 css 中的引号内

例子:

const Block = styled.div`
    &:before {
        display: absolute;
        top:0;
        content: '${props => props.before}'
    }
`

请注意,我使用的是ES6 new features,其中单个语句函数不需要使用花括号{}return

Codepen:https://codepen.io/metju/pen/zEKeOm

【讨论】:

  • 即使您已经返回了一个字符串,为什么还要将表达式包装在另一个引号中?例如content: ${props =&gt; props.test ? "foo" : " bar"}; 失败 content: '${props =&gt; props.test ? "foo" : " bar"}'; 工作
【解决方案2】:

我所做的是为此使用 css 辅助函数:

const Text = styled.span`
  &:before {
     ${props => !!props.before ?
      css`content: props.before;` : css`content: ' ?'';`
     };
  }
`

【讨论】:

    【解决方案3】:

    styled-components 和 sass 一样,没什么不同

    const Text = styled.span`
        &:before {
           content: ${props => !!props.before ? props.before : " ?"};
        }
    

    `;

    I am a // 呈现:“I am a ?”

    参考取自 Before and After pseudo classes used with styled-components

    【讨论】:

    • 我用过!!props.before,这是一个将字符串转换为布尔值的真实语句。只是为了检查您是否收到props.before
    • 感谢您的帮助!但是,它不起作用......我也试过这个。 &:before { 内容: ${props => !!props.before ? 'aaa' : "bbb"}; 'aaa' 和 'bbb' 都不会被渲染。
    • 当然,正如我在帖子中提到的,如果我这样写,它会起作用。 &:before { 内容:'12345' }
    猜你喜欢
    • 2021-01-24
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2012-02-04
    • 2014-01-29
    相关资源
    最近更新 更多