使用styled-components时出现'css is not defined'错误求助
问题排查与解决方案
问题根源
你遇到的'css' is not defined错误和React版本无关,核心原因是:css是styled-components官方提供的样式工具函数,但你的代码里没有从styled-components中导入它,导致ESLint识别不到这个变量。
两种解决方案
方案1:正确导入css函数
修改组件的import语句,同时导入css:
import React from "react"; import styled, { css } from "styled-components"; // 后续代码保持不变
导入后,原来的条件样式代码就能正常运行,css函数的作用是将样式片段转换为styled-components可解析的格式,在处理条件渲染样式时能避免解析异常,是官方推荐的写法。
方案2:移除css函数,直接返回样式字符串
如果不想使用css函数,也可以直接返回样式字符串,去掉所有css包裹:
const StyledButton = styled.button` border: none; border-radius: 4px; font-size: 1rem; font-weight: bold; padding: 0.25rem 1rem; color: white; outline: none; cursor: pointer; background: #343a40; &:hover { background: #868e96; } ${(props) => props.fullwidth && ` padding-top: 0.75rem; padding-bottom: 0.75rem; width: 100%; font-size: 1.125rem; `} ${(props) => props.cyan && ` background: #3bc9db; &:hover { background: #66d9e8; } `} `;
这种写法也能正常渲染样式,适合简单的条件场景。
额外注意事项
如果你之前删除css后仍报错,大概率是webpack缓存导致的,建议:
- 重启本地开发服务器
- 清除项目的缓存文件(比如
node_modules/.cache目录)
内容的提问来源于stack exchange,提问作者bluebear
相关产品推荐
相关产品推荐

