如何在样式表创建中使用 useTheme 钩子?

lan*_*rby 5 themes react-native react-native-paper

我想在组件内的样式表创建函数中使用来自我的本机纸张主题的颜色。这是我的代码

import { StyleSheet, Text, View } from 'react-native';
import { useTheme } from 'react-native-paper';

const Home = () => {
  const { colors } = useTheme();

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <Text>Home Page</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});


export default Home;
Run Code Online (Sandbox Code Playgroud)

我想在样式表中使用 backgroundColor: "#fff" 来引用来自 useTheme 钩子的 color.background。这可能吗?

map*_*008 28

我更喜欢这样使用它

const makeStyles = (colors: any) => StyleSheet.create({
   container: {
       backgroundColor: colors.red,
   }
})
Run Code Online (Sandbox Code Playgroud)

然后,在 render() 中

  const Home = () => {
  const { colors } = useTheme();
  const styles = makeStyles(colors)
  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <Text>Home Page</Text>
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 这将不必要地在每次重新渲染时创建一个新的样式表。为了避免这种情况,请将样式行添加更改为: const styles = useMemo(() =&gt; makeStyles(colors), [colors]); (3认同)