MUI styled组件报错:no-unused-expressions 寻求修复方案
修复React + MUI中的
no-unused-expressions报错 错误原因
你遇到的Line 5:5: Expected an assignment or function call and instead saw an expression no-unused-expressions报错,是因为MUI styled函数的使用语法错误。styled(Box)会返回一个用于创建样式组件的函数,你需要将样式规则作为参数传递给这个函数,而不是直接写一个孤立的字符串表达式。
修复方案
以下两种写法都可以解决问题,根据需求选择:
方案一:CSS模板字符串(推荐,支持完整CSS语法)
这种写法允许你使用标准的CSS语法,适合复杂样式场景:
import {Box, Table, TableBody, TableCell, TableHead, TableRow, Typography, styled} from '@mui/material'; // 核心修复:用模板字符串包裹样式,作为参数传给styled返回的函数 const Component = styled(Box)` width: 80%; // 可添加更多CSS规则,比如居中:margin: 0 auto; ` const Users = () => { return ( <Component> <Typography variant="h4">Users</Typography> <Box> <Table> <TableHead> <TableRow> <TableCell>Id</TableCell> <TableCell>Name</TableCell> <TableCell>Email</TableCell> <TableCell>Phone</TableCell> <TableCell>Salary</TableCell> <TableCell>Age</TableCell> <TableCell>Remove Entry</TableCell> </TableRow> </TableHead> <TableBody> <TableRow> <TableCell>101</TableCell> <TableCell>Code for Interview</TableCell> <TableCell>codeforinterview@gmail.com</TableCell> <TableCell>9998887765</TableCell> <TableCell>22000</TableCell> <TableCell>24</TableCell> <TableCell>Remove</TableCell> </TableRow> </TableBody> </Table> </Box> </Component> ) } export default Users;
方案二:样式对象(适合简单样式)
如果样式比较简单,也可以用React内联样式的对象写法:
import {Box, Table, TableBody, TableCell, TableHead, TableRow, Typography, styled} from '@mui/material'; // 核心修复:将样式写成对象,作为参数传给styled返回的函数 const Component = styled(Box)({ width: '80%' }) const Users = () => { return ( <Component> <Typography variant="h4">Users</Typography> <Box> <Table> <TableHead> <TableRow> <TableCell>Id</TableCell> <TableCell>Name</TableCell> <TableCell>Email</TableCell> <TableCell>Phone</TableCell> <TableCell>Salary</TableCell> <TableCell>Age</TableCell> <TableCell>Remove Entry</TableCell> </TableRow> </TableHead> <TableBody> <TableRow> <TableCell>101</TableCell> <TableCell>Code for Interview</TableCell> <TableCell>codeforinterview@gmail.com</TableCell> <TableCell>9998887765</TableCell> <TableCell>22000</TableCell> <TableCell>24</TableCell> <TableCell>Remove</TableCell> </TableRow> </TableBody> </Table> </Box> </Component> ) } export default Users;
关键说明
- 原代码中
styled(Box)后直接写'width: 80%'是无效的语法,JavaScript无法识别这个孤立的表达式,必须将样式通过括号传递给styled(Box)返回的函数。 - 模板字符串写法支持所有CSS特性,包括媒体查询、伪类等;对象写法需要将CSS属性转为驼峰命名(比如
background-color要写成backgroundColor)。
内容的提问来源于stack exchange,提问作者Aswin Shaji
相关产品推荐
相关产品推荐

