样式表中的平台条件语句(react-native)

Mar*_*ver 5 reactjs react-native

对于次要平台特定代码,您可以使用平台模块来执行一些平台相关代码。如此处的文档中所述:https : //facebook.github.io/react-native/docs/platform-specific-code.html

有一个如何在样式表中使用它的示例

var styles = StyleSheet.create({ 
   height: (Platform.OS === 'ios') ? 200 : 100, 
});
Run Code Online (Sandbox Code Playgroud)

我想做一些类似但简单的 if 语句来决定是否使用一种样式,例如仅用于一个平台的样式。

下面是一个例子:

var styles = StyleSheet.create({
   textInputStyle: {
      if (Platform.OS === 'android') {
         textAlignVertical:'top' // android only style
      }
   }
});~
Run Code Online (Sandbox Code Playgroud)

这在语法上是不正确的,实现这一目标的正确代码是什么。我想避免为每个平台使用两个单独的样式表,因为当它只有 1 或 2 个不同的字段时似乎没有必要。

Jov*_*van 6

我相信这就是你要找的:

var styles = StyleSheet.create({
   textInputStyle: {
      ...Platform.select({
        ios: {
            //
        },
        android: {
            //
        },
    }),
   }
})
Run Code Online (Sandbox Code Playgroud)

您提供的链接以上述代码为例。(v0.59)


age*_*unt 1

实现的一种方法是拥有两种不同的样式,然后在渲染中动态应用它。例如:

render(){
  let platformStyle = Platform.OS === 'ios' ? styles.iosStyle: styles.androidStyle;
  return (<View style={platformStyle}>
          .....
          </View>);
  }
  .....
  const styles = StyleSheet.create({
    iosStyle: {
    },
    androidStyle: {

    }
  });
Run Code Online (Sandbox Code Playgroud)