7

我有以下内容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>

我在这里做错了什么吗?

4

3 回答 3

15

你试过导入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;
于 2017-08-24T08:15:52.717 回答
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;
于 2018-12-17T22:09:51.070 回答
0

最后通过以下方式“弄清楚”:

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;

这有效......即使在我上面的问题中我完全遵循了文档。

于 2017-08-24T08:12:43.150 回答