【问题标题】:styled-components 'css' is not defined no-undef样式组件“css”未定义 no-undef
【发布时间】:2018-02-01 23:41:18
【问题描述】:

我有以下Button.js

import styled from 'styled-components';

const Button = styled.button`

    background: black;
    border: none;
    color: white;
    outline: none;

    ${props => props.add && css`
        background: palevioletred;
        color: white;
    `};

    ${props => props.delete && css`
        background: palevioletred;
        color: white;
    `};

`;

export default Button;

但是当我运行它时,在编译过程中出现以下错误:

./src/components/Button.js 第 10 行:'css' 未定义 no-undef 第 15 行:'css' 未定义 no-undef

然后我使用这样的按钮:

<Button delete>Delete</Button>
<Button add>Add</Button>

我在这里做错了什么?

【问题讨论】:

  • props =&gt; props.add &amp;&amp; css`...` 这是 js。此文件中未定义变量 css。也许styled.css`...`
  • @BalázsÉdes 我也是这么想的,但那行不通。

标签: javascript reactjs ecmascript-6 styled-components


【解决方案1】:

只需将 { css } 导入顶部!这在之前的评论中已经提到过。

import React from 'react';
import styled, { css } from 'styled-components';
//import './Button.css';

const Button = styled.button`
  background: white;
  border: 2px solid black;
  font-size: 1.2rem;
  color: black;

  ${props =>
    props.primary &&
    css`
      backround: blue;
    `}
`;

export default Button;

【讨论】:

    【解决方案2】:

    您是否尝试过导入 css?

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

    所以你的代码应该是

    import styled, { css } from 'styled-components';
    
    const Button = styled.button`
    
        background: black;
        border: none;
        color: white;
        outline: none;
    
        ${props => props.add && css`
            background: palevioletred;
            color: white;
        `};
    
        ${props => props.delete && css`
            background: palevioletred;
            color: white;
        `};
    
    `;
    
    export default Button;
    

    【讨论】:

    • 令人惊讶的是,他们的文档没有立即提及这一点,不得不复制示例并找到此答案。谢谢。
    【解决方案3】:

    终于“想通了”:

    import styled from 'styled-components';
    
    const Button = styled.button`
    
        background: black;
        border: none;
        color: white;
        outline: none;
    
        ${(props) => {
            if (props.add) {
                return 'background: green;'
            } else if (props.delete) {
                return 'background: red;'
            } else {
                return 'background: black;'
            }
        }}
    
    `;
    
    export default Button;
    

    这行得通...即使在我上面的问题中我遵循了文档完全

    【讨论】:

    • 你错过了导入 css
    猜你喜欢
    • 2021-04-26
    • 2021-03-20
    • 2021-10-16
    • 2018-06-09
    • 2018-10-02
    • 2021-05-26
    • 2021-06-17
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多