在样式组件中使用扩展运算符 [英] Using the spread operator in styled components

查看:41
本文介绍了在样式组件中使用扩展运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将扩展运算符与 React Native 中的样式组件一起使用?

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

我有这个组件:

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

但是可以说,在我的主题中,我有一个同时具有 fontFamily 和 fontSize 的对象,并且我在整个应用程序中都使用它.我想知道我是否可以做这样的事情,目前它不起作用:

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}
`;

例如在 iOS 中设置高程也很有用,因为我必须设置 4 种样式.

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

谢谢

推荐答案

您可以使用 css helper 函数生成特定的css并将其作为模板文字返回.

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
`

或有条件地作为

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

这篇关于在样式组件中使用扩展运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆