【问题标题】:Is ThemeProvider necessary for theming in styled components?ThemeProvider 是否需要在样式化组件中进行主题化?
【发布时间】:2021-01-23 21:13:25
【问题描述】:

我正在使用样式化组件,我想知道是否有必要使用 ThemeProvider。

这是文档中的示例。

// Define our button, but with the use of props.theme this time
const Button = styled.button`
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border-radius: 3px;

  /* Color the border and text with theme.main */
  color: ${props => props.theme.main};
  border: 2px solid ${props => props.theme.main};
`;

// We are passing a default theme for Buttons that arent wrapped in the ThemeProvider
Button.defaultProps = {
  theme: {
    main: "palevioletred"
  }
}

// Define what props.theme will look like
const theme = {
  main: "mediumseagreen"
};

render(
  <div>
    <Button>Normal</Button>

    <ThemeProvider theme={theme}>
      <Button>Themed</Button>
    </ThemeProvider>
  </div>
);

但我想知道我是否可以这样做:

// theme.js
const theme = {
  main: "mediumseagreen"
};
export default theme;


// main.js
import theme from 'theme';

const Button = styled.button`
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border-radius: 3px;

  /* Color the border and text with theme.main */
  color: ${theme.main};
  border: 2px solid ${theme.main};
`;

  render(
  <div>    
      <Button>Themed</Button>
  </div>
);

如果我不需要Normal Button(所有按钮都将是主题),并且我不需要动态主题(例如更改为暗模式),我可以使用第二种方法吗?有什么我没有想到的缺点吗?

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    是的,这是有效的代码。

    但它有一些缺点。 ThemeProvider 使用 React Context API 提供主题。通过 Context API,信息向下传递到组件树,以便每个孩子都可以访问上下文并可以访问包含的信息(在本例中为主题)。通过按照您建议的方式进行操作,您会遇到一些限制:

    1. 主题中的任何更改都不会反映在组件中,因为如果外部值发生更改,它们不会重新呈现。它们仅在属性和状态更改时重新渲染。 但正如你所写,你不需要那个
    2. 在每个要使用主题的组件中,都必须显式导入它,如果使用ThemeProvider,则不需要这样做;
    3. 如果您只想将主题应用到组件树的单个分支,那么很难跟踪您可以在哪里导入给定主题,在哪里不可以。特别是如果您在树的不同分支中重用组件。 但你说你只想为所有人使用一个主题。
    4. 这不是惯用的 react 代码,您的代码中至少会有一个 WTF?,这可能会减少您的 code quality

    【讨论】:

      猜你喜欢
      • 2021-12-07
      • 1970-01-01
      • 2020-10-23
      • 2017-08-05
      • 2018-05-28
      • 2023-02-07
      • 2021-07-17
      • 2011-07-09
      相关资源
      最近更新 更多