React项目中eslint react/destructuring-assignment报错解决咨询
解决ESLint Airbnb规则的
react/destructuring-assignment报错 这个报错是因为Airbnb的ESLint规则要求必须使用解构赋值获取对象嵌套属性,禁止直接链式访问(比如theme.colors.textSubtle这种写法)。针对你给出的代码,有两种合规修改方式:
方式1:组件参数层面解构
如果你的组件是通过props接收theme,可以直接在参数里解构出需要的属性:
// 原组件参数写法 const YourPopupComponent = ({ theme, removeThisPopup }) => { // ... return <StyledClose color={theme.colors.textSubtle} onClick={removeThisPopup} />; }; // 修改后 const YourPopupComponent = ({ theme: { colors: { textSubtle } }, removeThisPopup }) => { // ... return <StyledClose color={textSubtle} onClick={removeThisPopup} />; };
方式2:组件内部局部解构
如果不想在参数里深层解构,也可以在组件内部先提取需要的属性:
const YourPopupComponent = ({ theme, removeThisPopup }) => { // 先解构出需要的属性 const { colors: { textSubtle } } = theme; // ... return <StyledClose color={textSubtle} onClick={removeThisPopup} />; };
临时禁用规则(不推荐)
如果只是临时绕过这条规则,可以在报错行添加注释:
<StyledClose color={theme.colors.textSubtle} onClick={removeThisPopup} /> // eslint-disable-line react/destructuring-assignment
或者在文件顶部禁用整个规则(不建议,会破坏代码规范一致性):
/* eslint-disable react/destructuring-assignment */
内容的提问来源于stack exchange,提问作者RedRum
相关产品推荐
相关产品推荐

