我想在组件内的样式表创建函数中使用我的 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;
我想在样式表中使用backgroundColor: "#fff"来引用来自useTheme钩子的colors.background。这可能吗?
我更喜欢这样使用
const makeStyles = (colors: any) => StyleSheet.create({
container: {
backgroundColor: colors.red,
}
})
然后,在 render() 中
const Home = () => {
const { colors } = useTheme();
const styles = makeStyles(colors)
return (
<View style={[styles.container, { backgroundColor: colors.background }]}>
<Text>Home Page</Text>
</View>
);
}
https://stackoverflow.com/a/65259425/8142053
我最近从 StackOverflow 找到了这个答案,根据该答案,您可以编写一个 customHook 并在自定义钩子中使用它。请查看他的回答以获得清晰的理解。
import {Theme, useTheme} from '@react-navigation/native';
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
function HomeScreen(): React.JSX.Element {
const theme = useTheme();
const styles = makeStyles(theme);
return (
<View style={styles.container}>
<Text>Home</Text>
</View>
);
}
const makeStyles = ({colors}: Theme) =>
StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
alignItems: 'center',
justifyContent: 'center',
},
});
export default HomeScreen;
这应该适用于 tsx