Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

javascript - Using the spread operator in styled components

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...