如何解决SonarQube代码重复行问题?
解决SonarQube代码重复行问题
问题原因
SonarQube报重复行,本质是代码里存在冗余的重复片段。从你提供的TextInput组件看,重复点集中在:
- 重复定义相同的样式规则(比如两处设置
MuiFormLabel-root.Mui-focused的颜色,还出现了颜色冲突) - 重复的字体族、边框色等样式值
- 下划线隐藏逻辑在
after和before伪元素中完全重复
修复步骤
1. 提取重复值为变量
把重复使用的样式常量抽出来,既减少重复代码,也方便后续统一维护:
import React from "react"; import { OutlinedInputProps, TextField, TextFieldProps, alpha, styled } from "@material-ui/core"; // 提取重复的样式变量 const FOCUSED_LABEL_COLOR = "#9D9D9D"; const FONT_FAMILY = "Montserrat"; const BORDER_COLOR = "#FEE7D7"; const HIDDEN_UNDERLINE = { borderBottom: '0px' }; const TextInput = styled((props: TextFieldProps) => ( <TextField InputProps={{ disableUnderline: true, sx: { '& input::placeholder': { color: "red !important" } } as Partial<OutlinedInputProps> }} {...props} /> ))(({ theme }) => ({ '& .MuiFilledInput-root': { border: `1px solid ${BORDER_COLOR}`, width: '410px', overflow: 'hidden', borderRadius: "8px", backgroundColor: '#fcfcfb', fontFamily: FONT_FAMILY, transition: theme.transitions.create([ 'border-color', 'background-color', 'box-shadow', ]), '&:hover': { backgroundColor: 'transparent', }, '&.Mui-focused': { backgroundColor: 'transparent', boxShadow: `${alpha(BORDER_COLOR, 0.25)} 0 0 0 2px`, borderColor: BORDER_COLOR, }, }, '& .MuiFilledInput-underline:after': HIDDEN_UNDERLINE, '& .MuiFilledInput-underline:before': HIDDEN_UNDERLINE, '& .MuiFormLabel-root.Mui-focused': { color: FOCUSED_LABEL_COLOR, }, '& .MuiInputLabel-filled.MuiInputLabel-shrink': { transform: 'translate(12px, 9px) scale(0.88)' }, '& .MuiFormHelperText-root.MuiFormHelperText-contained.Mui-error':{ fontFamily: `${FONT_FAMILY} !important`, fontSize: "8px", lineHeight: "12px", }, '& .MuiFormLabel-root.MuiInputLabel-root.MuiInputLabel-formControl.MuiInputLabel-animated.MuiInputLabel-filled':{ fontFamily: `${FONT_FAMILY}!important`, color: FOCUSED_LABEL_COLOR, } })); export default TextInput;
2. 删除冲突的重复样式
原代码中& .MuiFilledInput-root内部嵌套的.MuiFormLabel-root.Mui-focused样式和外部的重复,且颜色不一致(内部设为red,外部是#9D9D9D),直接删除内部的这部分冗余代码,保持样式统一。
3. 处理跨文件重复(如果涉及)
如果SonarQube提示重复的代码来自其他组件:
- 把通用的styled逻辑抽成独立的工具函数或样式文件
- 封装基础输入组件,其他同类组件基于基础组件扩展,避免重复编写相同的样式结构
验证修复
推送修改后的代码到GitLab,触发流水线:
- 确认SonarQube检测的代码重复率降至0%
- 检查组件的UI展示、交互逻辑和修改前一致,无样式异常
内容的提问来源于stack exchange,提问作者jenish963
相关产品推荐
相关产品推荐

