如何在样式组件中使用{withTheme}?请任何人给出实时示例

Riz*_*wan 2 reactjs styled-components

实际上,我不明白如何在样式组件中使用 {withTheme} 及其用法。因此,任何人都可以在样式组件中使用 {withTheme} 提供正确的代码。

hur*_*ane 6

withTheme正在帮助您从组件道具中获取主题变量。当您定义主题时,您通常可以在样式化组件中使用它们,但是如果您使用withThemeHOC 定义组件,则可以在组件中使用这些变量。

// Define our button, with the use of props.theme
const Button = styled.button`
  color: ${props => props.theme.fg};
  border: 2px solid ${props => props.theme.fg};
  background: ${props => props.theme.bg};
`;

// Define our button, but with the use of component.props
const ThemeButton = (props) => (
  <button style={{background: props.theme.bg, color: props.theme.fg, border: `1px solid ${props.theme.fg}`}}>
  {`this button is using: ${props.theme.fg} and ${props.theme.bg}`}
  </button>
)

const ButtonWithTheme = withTheme(ThemeButton);

// Define our `fg` and `bg` on the theme
const theme = {
  fg: "palevioletred",
  bg: "white"
};

<ThemeProvider theme={theme}>
  <div>
    <Button>Default Theme</Button>
    <ButtonWithTheme></ButtonWithTheme>
  </div>
</ThemeProvider>
Run Code Online (Sandbox Code Playgroud)

您可以在这里查看https://codesandbox.io/s/zealous-sky-kgjqj?fontsize=14