无法使用样式化组件获取媒体模板

Can not get media templates working using styled-components

我对样式组件还很陌生,我正在尝试让媒体模板在我的 React 应用程序中工作。它是使用“create-react-app”创建的 我遵循了 styled-components 文档中发布的代码:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import styled from 'styled-components';

const sizes = {
    desktop: 992,
    tablet: 768,
    phone: 376
}

// Iterate through the sizes and create a media template
const media = Object.keys(sizes).reduce((acc, label) => {
    acc[label] = (...args) => css`
         @media (max-width: ${sizes[label] / 16}em) {
            ${css(...args)}
         }
    `

    return acc
}, {})

const Content = styled.div`
    height: 3em;
    width: 3em;
    background: papayawhip;

/* Now we have our methods on media and can use them instead of raw 
queries */
    ${media.desktop`background: dodgerblue;`}
    ${media.tablet`background: mediumseagreen;`}
    ${media.phone`background: palevioletred;`}
`;

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          header goes here!!!
        </div>
        <Content/>
      </div>
    );
  }
}

export default App;

尽管如此,我收到以下错误:

第 14 行:'css' 未定义 no-undef

第 16 行:'css' 未定义 no-undef

第 14 行如下:acc[label] = (...args) => css`

那一行有什么问题? 我得到这段代码的 link 是 here

很抱歉给您带来麻烦 运行。您唯一需要更改的是从 styled-components!

导入 the css helper
import styled, { css } from 'styled-components';

这将解决问题。

我建议阅读 our documentation so you're aware of the features the library has. It's not very long but it'll set you up for success. We'll also update the documentation to include the full import! (reference issue)