使用 Stylesheet.create 反应原生元素

Shi*_*pta 6 react-native react-native-elements

我正在尝试将react-native-elements 与我的React-Native 应用程序一起使用。

\n

我有一个包含主题详细信息的中央 js 文件,这些文件是使用 ThemeProvider 注入的,如此处所述 - https://react-native-elements.github.io/react-native-elements/docs/customization.html

\n

但是,当我尝试在组件的 stylesheet.create 方法中使用传递的主题时,出现错误。我究竟做错了什么?-

\n
import React from \'react\';\nimport {View, StyleSheet} from \'react-native\';\nimport {Text, withTheme} from \'react-native-elements\';\n\nconst Header = props => {\n  const {theme} = props;\n\n  return (\n    <View style={styles.container}>\n      <Text>Home</Text>\n    </View>\n  );\n};\nconst styles = StyleSheet.create({\n  container: {\n    width: \'100%\',\n    backgroundColor: theme.container.backgroundColor,//**** Getting error here stating that theme is not defined\n    shadowRadius: 1.5,\n    elevation: 2,\n    shadowColor: \'rgb(0,0,0)\',\n    shadowOpacity: 0.4,\n    shadowOffset: {width: 0, height: 2.5},\n  },\n});\n\nexport default withTheme(Header);\n
Run Code Online (Sandbox Code Playgroud)\n

如果我可以提供更多详细信息,请告诉我。

\n
\n

更新:

\n

感谢下面提供的建议 @Sebastian Bergl\xc3\xb6nn ,我能够将其参数化,而无需通过这样做导出到不同的文件 -

\n
const Header = props => {\n  const {theme} = props;\n\n  return (\n    <View style={styles(theme).container}>\n      <Text>Home</Text>\n    </View>\n  );\n};\nconst styles = theme =>\n  StyleSheet.create({\n    container: {\n      width: \'100%\',\n      backgroundColor: theme.container.backgroundColor,\n      shadowRadius: 1.5,\n      elevation: 2,\n      shadowColor: \'rgb(0,0,0)\',\n      shadowOpacity: 0.4,\n      shadowOffset: {width: 0, height: 2.5},\n    },\n  });\n
Run Code Online (Sandbox Code Playgroud)\n

try*_*ryp 5

我可以建议您使用带有样式表的函数的更简洁的方法。该方法类似于第一个主题给出的建议,但我们不使用全局样式表变量,而是仅在所需的样式上使用变量:

  container: theme => ({
      flex: 1,
      backgroundColor: theme.colors.backgroundPrimary
   }),
Run Code Online (Sandbox Code Playgroud)

在你看来,用法也很干净:

<View style={styles.container(theme)}>
Run Code Online (Sandbox Code Playgroud)

然而,这两种解决方案都非常有效,请选择最符合您需求的一个:)


Tha*_*hik 4

从代码来看,代码theme是在标头组件内部定义的,所以它显示主题未定义。

要应用主题中的背景颜色,您可以执行以下操作:

const Header = props => {
  const {theme} = props;

  return (
    <View style={[styles.container,{backgroundColor: theme.container.backgroundColor}]}>
      <Text>Home</Text>
    </View>
  );
};
Run Code Online (Sandbox Code Playgroud)

并且不要忘记从样式表中删除背景颜色。

const styles = StyleSheet.create({
  container: {
    width: '100%',
    //backgroundColor: theme.container.backgroundColor,
    shadowRadius: 1.5,
    elevation: 2,
    shadowColor: 'rgb(0,0,0)',
    shadowOpacity: 0.4,
    shadowOffset: {width: 0, height: 2.5},
  },
});
Run Code Online (Sandbox Code Playgroud)

  • @ShibasisSengupta 您可以导出带有参数(例如 bg-color)的函数,并返回样式表。示例:/sf/ask/2989512921/ (2认同)