我有一个这样的theme:
export const theme = {
red: "#CF3721",
darkGrey: "#191919",
white: "#fff",
blue: "#31A9B8",
};和一个ThemeProvider
<ThemeProvider theme={theme}>
<Navigator />
</ThemeProvider>我怎么才能进入f.e。到下面的red color内部的styles?我试过这样的方法,但效果不太好。我正在使用React Native。
<Component
styles={{
fontSize: 20,
color: `${({ theme }) => theme.red}`,
}}
/>发布于 2021-12-04 13:43:12
react-theme-provider库导出useTheme钩子和withTheme HOC。您可以使用其中之一访问主题上下文。
const { ThemeProvider, withTheme, useTheme } = createTheming(defaultTheme);如果使用功能组件,则可以使用useTheme钩子。
function App() {
const theme = useTheme();
return (
<Component
styles={{
fontSize: 20,
color: theme.red,
}}
/>
);
}如果您使用的是类组件,则可以使用withTheme自定义。
class App extends React.Component {
render() {
return (
<Component
styles={{
fontSize: 20,
color: this.props.theme.red,
}}
/>
);
}
}
export default withTheme(App);您可以在文档中查找更高级的用法。https://github.com/callstack/react-theme-provider
https://stackoverflow.com/questions/70225881
复制相似问题