在 ThemeProvider React Native 中获取颜色

Getting access to a color in ThemeProvider React Native

我有一个 theme 这样的:

export const theme = {
  red: "#CF3721",
  darkGrey: "#191919",
  white: "#fff",
  blue: "#31A9B8",
};

和一个ThemeProvider:

<ThemeProvider theme={theme}>
  <Navigator />
</ThemeProvider>

如何获得访问权限 f.e。到下面 styles 里面的 red color?我尝试过类似的方法,但效果不佳。我正在使用 React Native.

<Component
    styles={{
            fontSize: 20,
            color: `${({ theme }) => theme.red}`,
           }}
/>

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,
      }}
    />
  );
}

如果您正在使用 Class 组件,您可以使用 withTheme HOC。

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