Using the spread operator in styled components

江枫思渺然 提交于 2020-07-05 09:45:06

问题


Is it possible to use the spread operator with a styled component in React Native?

I have this component:

const StyledHeaderText = styled.Text`
fontFamily: ${props => props.theme.font};
fontSize: ${props => props.theme.fontSizeSubtitle};
color: ${props => (props.lightMode) ? props.theme.fontColor : props.theme.fontPrimaryColor}
`;

But lets say that in my theme, I have an object that has both the fontFamily and the fontSize, and I re use all over the app. I would like to be able to know if I can do something like this, which currently it is not working:

const StyledHeaderText = styled.Text`
...${props => props.theme.fontHeader};
color: ${props => (props.lightMode) ? props.theme.fontColor : props.theme.fontPrimaryColor}
`;

This would be useful too setting up elevation in iOS for example, since I have to setup 4 styles.

Thanks


回答1:


You can use the css helper function to generate the specific css and return it as a template literal.

import styled, {css} from 'styled-components/native'

const GlobalStyles = css`
 fontFamily: ${props => props.theme.font};
 fontSize: ${props => props.theme.fontSizeSubtitle};
`

const StyledHeaderText = styled.Text`
 ${GlobalStyles}
 // Other Styles
`

or conditionally as

const StyledHeaderText = styled.Text`
 ${props => props.theme.fontHeader ? GlobalStyles : 'fontSize: 14'}
 // Other Styles
`



回答2:


You can also return objects directly from interpolations function, and they'll be treated as inline styles.

const StyledHeaderText = styled.Text`
      ${props => ({...props.theme.fontHeader})};
      color: ${props => (props.lightMode) ? props.theme.fontColor props.theme.fontPrimaryColor}
`;

or

const StyledHeaderText = styled.Text`
          ${props => props.theme.fontHeader};
          color: ${props => (props.lightMode) ? props.theme.fontColor props.theme.fontPrimaryColor}
    `;

for more details : reference



来源:https://stackoverflow.com/questions/53210171/using-the-spread-operator-in-styled-components

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