我正在创建将呈现各种SVG的React组件:
const Close = ({
fill, width, height, float,
}) => (
<svg width={ `${width}px` } height={ `${height}px` } viewBox="0 0 14.48 14.48" style={ { float: `${float}`, cursor: 'pointer' } }>
<title>x</title>
<g id="Layer_2" data-name="Layer 2">
<g id="Background">
<line style={ { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 } } x1="14.13" y1="0.35" x2="0.35" y2="14.13" />
<line style={ { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 } } x1="14.13" y1="14.13" x2="0.35" y2="0.35" />
</g>
</g>
</svg>
);
Run Code Online (Sandbox Code Playgroud)
能够提供各种属于该组件的尺寸,颜色等,非常方便...
然而,我没有一个好的解决方案是以干燥的方式处理样式.请注意,line元素具有相同的值style.我现在把它们写成内联,因为如果我添加了一个嵌入式样式表,那么我会在页面的其他地方呈现其他SVG的类名冲突(我们的SVG软件反复使用相同的类).
<style scoped>已从规范中删除:https://github.com/whatwg/html/issues/552
Edge尚不支持Shadow DOM:https://caniuse.com/#feat=shadowdomv1
范围风格还有其他选择吗?
如果您只想干燥代码,您可以创建一个样式对象并重用它:
const Close = ({
fill, width, height, float,
}) => {
const style = { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 }
return (
<svg width={ `${width}px` } height={ `${height}px` } viewBox="0 0 14.48 14.48" style={ { float: `${float}`, cursor: 'pointer' } }>
<title>x</title>
<g id="Layer_2" data-name="Layer 2">
<g id="Background">
<line style={ style } x1="14.13" y1="0.35" x2="0.35" y2="14.13" />
<line style={ style } x1="14.13" y1="14.13" x2="0.35" y2="0.35" />
</g>
</g>
</svg>
);
}
Run Code Online (Sandbox Code Playgroud)
这也会导致性能的小幅提升,因为每个渲染周期中创建的对象会更少。
| 归档时间: |
|
| 查看次数: |
265 次 |
| 最近记录: |