能否通过.svgrrc文件修改SVG的stroke-width属性?
如何通过.svgrrc修改SVG的stroke-width属性
是的,可以通过.svgrrc修改SVG的stroke-width属性,你当前配置未生效的核心原因是SVGR对stroke-width这类短横线命名属性的处理逻辑和fill/stroke不同,再加上默认集成的SVGO优化会干扰属性值匹配,导致规则失效。以下是两种可行的解决方法:
方法一:调整匹配规则并禁用SVGO单位优化
SVGO默认会自动移除stroke-width属性的冗余单位(比如把1px转换成1),直接导致你写的"1px"匹配规则失效。你需要先禁用该优化,再调整匹配值:
修改.svgrrc配置如下:
{ "replaceAttrValues": { "#000": "{props.fill}", "#001": "{props.stroke}", "1": "{props.strokeWidth}" }, "svgoConfig": { "plugins": [ { "cleanupNumericValues": { "defaultPx": false, // 禁用自动移除px单位的优化 "convertToPx": false } } ] } }
同时将SVG文件中的stroke-width="1px"改为stroke-width="1",确保匹配值和原始属性值一致。
方法二:使用自定义SVGR插件(更稳定)
如果上述方法仍有问题,可以通过自定义插件直接修改属性节点,确保stroke-width被转为接收props的形式:
- 创建自定义插件文件
svgr-plugin-stroke-width.js:
module.exports = () => { return { visitor: { Element(path) { const attrs = path.node.attributes; for (let i = 0; i < attrs.length; i++) { const attr = attrs[i]; if (attr.name.name === 'stroke-width') { // 将属性值替换为props.strokeWidth,可添加默认值 attr.value = { type: 'JSXExpressionContainer', expression: { type: 'LogicalExpression', operator: '||', left: { type: 'MemberExpression', object: { type: 'Identifier', name: 'props' }, property: { type: 'Identifier', name: 'strokeWidth' }, }, right: { type: 'Literal', value: 1 }, // 默认值设为1 }, }; } } }, }, }; };
- 在
.svgrrc中引入该插件:
{ "replaceAttrValues": { "#000": "{props.fill}", "#001": "{props.stroke}" }, "plugins": ["./svgr-plugin-stroke-width.js"] }
验证方式
生成React组件后,你可以通过以下方式传入strokeWidth属性:
<YourIcon fill="#fff" stroke="#000" strokeWidth={2} />
检查生成的组件代码,确认strokeWidth属性是否正确接收props值。
内容的提问来源于stack exchange,提问作者Sagar Mandal
相关产品推荐
相关产品推荐

