如何在React项目中渲染@svgr/core动态生成的SVG组件
问题核心原因
你当前遇到两个核心障碍:
@svgr/core返回的jsCode是字符串格式的JS代码,不是可直接渲染的React组件,需要先转成可执行的函数组件- 转换是异步操作,你没有把转换后的组件存储到状态中,渲染逻辑也没有引用转换结果
解决代码示例
import { useState, useEffect } from 'react' import svgr from '@svgr/core' const ColorPicker = (props) => { // 存储转换完成的SVG组件 const [SvgComponent, setSvgComponent] = useState(null) useEffect(() => { if (!props.svg) return svgr(props.svg, { icon: true }, { componentName: 'MyComponent' }).then( (jsCode) => { try { // 把字符串代码转为可执行组件,适配svgr默认的export default输出格式 const module = {} const getComponent = new Function('module', 'React', `${jsCode}; return module.default;`) const ExecutableComponent = getComponent(module, React) setSvgComponent(() => ExecutableComponent) } catch (err) { console.error('SVG转组件失败:', err) } }, ) }, [props.svg]) // svg内容变化时自动重新转换 return ( <div className="colorpickerdisplay"> <button className="Color1"/> {/* 渲染转换后的组件,支持透传自定义props */} {SvgComponent && <SvgComponent {...props} />} </div> ) } export default ColorPicker;
注意事项
- 安全提示:该方案仅适用于SVG来源完全可控的场景(比如仅你方后台存储的静态SVG),如果支持用户上传SVG,直接执行转换后的代码会存在XSS注入风险
- 如果数据库中存储的SVG是固定可枚举的,更推荐提前用
@svgr/cli批量转成静态组件文件直接引入,性能和安全性都更高 - 生成的SVG组件支持直接传
className、width、fill等props自定义样式,@svgr默认会把所有属性透传到SVG根节点
内容的提问来源于stack exchange,提问作者banbz
相关产品推荐
相关产品推荐

