[英]styled-components 'css' is not defined no-undef
我有以下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>
我在這里做錯了什么?
您是否嘗試導入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;
最后,通過以下步驟“弄清楚了”:
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}導入頂部即可! 前面的評論中曾提到過這一點。
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.