How to render pseudo before content dynamically in styled-component

♀尐吖头ヾ 提交于 2020-01-03 12:58:42

问题


I'm having a trouble of rendering pseudo before content dynamically in styled-components.

Am I doing something wrong?

I have no problem when I render pseudo before content statically, but it doesn't work when I try it dynamically.

React Component

const Test = (props) => {

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

};

Styled Component(Not Work)

const Text = styled.span`

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


`;

Styled Component(This works fine)

const Text = styled.span`

    &:before {
        content: '12345'
    }


`;

回答1:


That is because content value must be within quotes in css

Here is the working CSS

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

Please note that I am leveraging ES6 new features wherein a single statement function there is no need to use curly braces {} and return.

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




回答2:


styled-components works the same as in sass, nothing different

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

`;

I am a // renders: "I am a 🦄"

Reference taken from Before and After pseudo classes used with styled-components




回答3:


What I did is use the css helper function for this:

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


来源:https://stackoverflow.com/questions/46339034/how-to-render-pseudo-before-content-dynamically-in-styled-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!