我从服务器获取 svg 代码,我必须更改某些特定路径的 Id。
(例如,在下面的代码中,我想向预处理器添加一些内容,以将已操作的路径的 Id 更改为“targetPath”,以便我可以访问 useEffect Hook 中的路径。)
import React, { useEffect, useState } from 'react';
import SVG from 'react-inlinesvg';
const PaintObject = ({ objectdata, selectedColor }) => {
const [loaded, setLoaded] = useState(false);
const [color, setColor] = useState('#fff');
useEffect(() => {
if (loaded) {
const path = document.getElementById('targetPath');
path
&& path.addEventListener(
'click',
() => setColor(selectedColor),
false,
);
}
}, [loaded, selectedColor]);
return (
<SVG
src={objectdata.image}
style={{ color }}
onLoad={() => setLoaded(true)}
preProcessor={(code) => code.replace('fill="#fff"', 'fill="currentcolor"')}
/>
);
};
export default PaintObject;
最佳答案
.replace(/id=".*?"fill="currentcolor"/, 'id="targetPath"fill="currentcolor"')
将其添加到预处理器就是解决方案。
关于javascript - 如何更改 svg 文件中的路径 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65263466/