React表格中通过Props传入颜色代码检测类型并渲染颜色
解决React表格中颜色渲染与格式检测问题
一、修复当前颜色渲染的错误
你的代码里有个明显问题:backgroundColor: { color } 会把颜色值包装成对象,导致样式不生效,应该直接使用字符串值 color。另外当前span尺寸过小,几乎无法识别,建议调整为更清晰的尺寸,比如宽40px、高20px,再加个边框增强对比。
二、实现RGB/HEX格式检测
可以通过正则表达式自行实现格式检测,无需额外依赖。下面是一个实用的工具函数:
const detectColorFormat = (color) => { // 匹配HEX格式:支持3位、4位、6位、8位(含透明度) const hexPattern = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/; // 匹配RGB/RGBA格式:支持空格分隔、带透明度的情况 const rgbPattern = /^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*(?:0(?:\.\d+)?|1(?:\.0+)?))?\s*\)$/; if (hexPattern.test(color)) return 'HEX'; if (rgbPattern.test(color)) return 'RGB/RGBA'; return '未知格式'; };
三、更新后的ColorList组件
把工具函数整合进组件,同时修复样式和依赖项问题:
const ColorList = () => { const dispatch = useDispatch(); const { user } = useSelector((state) => state.auth); const { colors } = useSelector((state) => state.color); React.useEffect(() => { if (user?.refreshToken) { // 增加空值判断,避免无意义的请求 dispatch(getColors(user.refreshToken)); } }, [dispatch, user?.refreshToken]); // 依赖项加入refreshToken,避免重复触发 // 颜色格式检测函数 const detectColorFormat = (color) => { const hexPattern = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/; const rgbPattern = /^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(?:,\s*(?:0(?:\.\d+)?|1(?:\.0+)?))?\s*\)$/; if (hexPattern.test(color)) return 'HEX'; if (rgbPattern.test(color)) return 'RGB/RGBA'; return '未知格式'; }; return ( <div className="container-xxl"> <div className="row"> <div className="col-12"> <table className="table table-striped table-hover"> <thead> <tr> <th scope="col">#</th> <th scope="col">名称</th> <th scope="col">颜色代码</th> <th scope="col">格式</th> <th scope="col">预览</th> </tr> </thead> <tbody> {colors.map(({ color, name }, index) => ( <tr key={index}> <th scope="row">{index + 1}</th> <td>{name}</td> <td>{color}</td> <td>{detectColorFormat(color)}</td> <td> <span style={{ display: 'inline-block', backgroundColor: color, width: '40px', height: '20px', border: '1px solid #ddd', borderRadius: '4px' }} ></span> </td> </tr> ))} </tbody> </table> </div> </div> </div> ); };
四、可选:使用工具库增强功能
如果需要更复杂的颜色处理(比如格式转换、有效性验证),可以使用成熟工具库color.js:
- 安装依赖:
npm install color - 在组件中使用:
import Color from 'color'; const isValidColor = (color) => { try { new Color(color); return true; } catch (e) { return false; } }; const getColorFormat = (color) => { try { const c = new Color(color); if (c.format() === 'hex') return 'HEX'; if (c.format() === 'rgb') return 'RGB/RGBA'; return c.format(); } catch (e) { return '未知格式'; } };
内容的提问来源于stack exchange,提问作者code46
相关产品推荐
相关产品推荐

