首页 > 解决方案 > 在 css 语句中反应原生样式表多个值

问题描述

我认为这个问题最好用一个例子来描述:

假设我想将边距应用于这样的元素:

const myView = () => <View style={styles.viewStyle}></View>

const styles = StyleSheet.create({
  viewStyle: {
    margin: "0 0 5 10",
  },
})

是否可以在没有多个保证金声明的情况下做到这一点?
谢谢阅读。

标签: javascriptcssreactjsreact-native

解决方案


我不认为你可以,除非你写一个函数来做这样的事情。像这样:

const CommonStyle = {
   margin: (t, r, b, l) => {
        marginTop: t,
        marginRight: r,
        marginBottom: b,
        marginLeft: l,
   }
}

然后按照你的风格:

const styles = StyleSheet.create({
  viewStyle: {
    ...CommonStyle.margin(0, 0, 5, 10),
  },
})

但是,在最常见的情况下,我们最多只更改 2 个方向的边距。当您习惯了样式时,有多种选项可以快速为您的组件设置样式。例子:

“5 10 5 10”等于

{
  marginVertical: 5,
  marginHorizontal: 10,
}

“0 0 0 5”等于

{
  margin: 0,
  marginLeft: 5,
}

推荐阅读