2017-07-01 26 views
0

我對樣式化組件非常陌生,我試圖讓媒體模板在我的反應應用程序中工作。它是用「create-react-app」 創建我也跟着張貼在風格的組件文檔代碼:無法使用樣式化組件獲取媒體模板

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」沒有定義沒有民主基金

線16: '樣式表' 沒有定義無爲undef

線14如下:ACC [標號] =(...參數)=> css`

那條線有什麼問題? 我得到這段代碼的那段代碼的鏈接是here

回答

2

對不起,你遇到了麻煩。唯一需要更改的是從styled-components導入the css helper

import styled, { css } from 'styled-components'; 

這會解決它。

我建議您閱讀our documentation,以便您瞭解圖書館的功能。這不是很長,但它會讓你成功。我們還會更新文檔以包含完整的導入! (reference issue

+1

非常感謝。我已經添加了css作爲導入,但由於無關的JavaScript錯誤,我無法使其工作。話雖如此,風格的組件是有據可查的,工程,使組件化真的工作。它只是石頭。 – ErnestoDeLucia

+1

謝謝你的客氣話,很高興你喜歡它! – mxstbr