在样式化组件中模拟主题

时间:2018-10-05 14:52:00

标签: javascript reactjs styled-components

我的测试失败了,因为我的样式化组件使用的是从样式化组件<ThemeProvider />传递的主题

但是当我这样做时:

background-color: ${({ theme }) => theme.backgroundColor};

没关系

但是当我这样做

background-color: ${({ theme }) => theme.background.color};

它炸毁了说它不能read color of undefined,我很困惑为什么它允许一个而不允许另一个?

在代码本身中,它可以正常工作,但测试失败,如何传递主题,以便所有测试再次通过?

为什么它适用于第一个而不是第二个?

1 个答案:

答案 0 :(得分:1)

这是因为未在主题对象中定义背景,并且您收到一条错误消息cannot read property color of undefined。您可以覆盖/向主题添加一些属性。您必须在主题中添加background.color。有关如何为主题定义和使用一些属性的信息,请参见styled-component theming

这是有关样式组件文档的示例:

// Define what props.theme will look like. this object can be imported as a global theme options.
const theme = {
  backgroundColor: "yellow", // -> `props.theme.backgroundColor
  // or
  background: { color: 'green' } // -> `props.theme.background.color
};  


// We are passing a default theme for Buttons that aren't wrapped in the ThemeProvider
Button.defaultProps = {
  theme: {
    backgroundColor: "red"
  }
}


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

  /* setting the background-color value from Theme options */
  background-color: ${props => props.theme.backgroundColor};
`;


render(
  <div>
    <Button> My background color would be 'Red' </Button>

    // Use <ThemeProvider /> to wrap your theme options to your components/elements.

    <ThemeProvider theme={theme}>
      <Button> My background color would be 'Yellow' </Button>
    </ThemeProvider>
  </div>
);
相关问题