在样式组件中使用扩展运算符

sfr*_*ini 6 javascript react-native styled-components

是否可以将扩展运算符与 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}
`;
Run Code Online (Sandbox Code Playgroud)

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

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

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

谢谢

Pri*_*dya 10

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

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
`
Run Code Online (Sandbox Code Playgroud)

或有条件地作为

const StyledHeaderText = styled.Text`
 ${props => props.theme.fontHeader ? GlobalStyles : 'fontSize: 14'}
 // Other Styles
`
Run Code Online (Sandbox Code Playgroud)