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

标签 reactjs styled-components

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

最佳答案

withTheme 可帮助您从组件属性中获取主题变量。当您定义一个主题时,您通常可以在样式组件中使用它们,但如果您使用 withTheme HOC 定义您的组件,您可以在您的组件中使用这些变量。

// 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>

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

关于reactjs - 如何在样式组件中使用 {withTheme}。?任何人请给出实时示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56947677/

相关文章:

javascript - 如何测试按钮是否被点击?

reactjs - Firebase 身份验证和 React Hook - 从钩子(Hook)返回的函数不起作用

javascript - react Hook : Handling Objects as dependency in useEffects

javascript - 无法让样式组件将 Logo 置于屏幕中央?

javascript - 模板文字中的多次评估...如何改进样式组件的填充计算?

javascript - 如何在 next.js 应用中使用谷歌分析?

javascript - 样式化组件在重新渲染后不会更新 <div>

javascript - React JS TreeView 显示api响应

javascript - JSX 中的 bool 复选框值不起作用

reactjs - 如何修复 'Static HTML elements with event handlers require a role.'?