我有一个SVG文件,我想在反应组件中用作图标。
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 409.6 405.76"><defs><style>.cls-1{fill:none;}.cls-2{clip-path:url(#clip-path);}</style><clipPath id="clip-path" transform="translate(-478 -181.08)"><rect class="cls-1" x="478" y="181" width="409.92" height="406.8"/></clipPath></defs><title>test</title><g class="cls-2"><path class="ofj" d="M682.8,396.06c50.72,0,91.84-48.13,91.84-107.49,0-82.33-41.12-107.49-91.84-107.49S591,206.24,591,288.57c0,59.36,41.12,107.49,91.84,107.49Zm0,0" transform="translate(-478 -181.08)"/><path d="M885.6,554.28,839.27,449.9a23.3,23.3,0,0,0-10.48-11.15l-71.91-37.43a4.66,4.66,0,0,0-4.93.41,113.41,113.41,0,0,1-138.3,0,4.67,4.67,0,0,0-4.94-.41l-71.9,37.43a23.24,23.24,0,0,0-10.47,11.15L480,554.28a23.16,23.16,0,0,0,21.18,32.56H864.42a23.17,23.17,0,0,0,21.18-32.56Zm0,0" transform="translate(-478 -181.08)"/></g></svg>
我希望能够动态更改填充颜色。我已经读过,最好使用SVG&#39; inline&#39;我尝试用<use>
引用它但它不起作用(它没有显示......)
<svg className="icon-avator">
<use xlinkHref="./assets/avatar.svg" />
</svg>
我怎样才能做到这一点?
答案 0 :(得分:5)
React JSX可以生成SVG,就像它对HTML一样。将SVG编写为组件&#34;标记&#34;,并使用props来控制fill
属性(您也可以更改样式):
const Icon = ({ fill }) => (
<svg viewBox="0 0 409.6 405.76" fill={ fill }>
<path d="M682.8,396.06c50.72,0,91.84-48.13,91.84-107.49,0-82.33-41.12-107.49-91.84-107.49S591,206.24,591,288.57c0,59.36,41.12,107.49,91.84,107.49Zm0,0" transform="translate(-478 -181.08)"/>
<path d="M885.6,554.28,839.27,449.9a23.3,23.3,0,0,0-10.48-11.15l-71.91-37.43a4.66,4.66,0,0,0-4.93.41,113.41,113.41,0,0,1-138.3,0,4.67,4.67,0,0,0-4.94-.41l-71.9,37.43a23.24,23.24,0,0,0-10.47,11.15L480,554.28a23.16,23.16,0,0,0,21.18,32.56H864.42a23.17,23.17,0,0,0,21.18-32.56Zm0,0" transform="translate(-478 -181.08)"/>
</svg>
);
ReactDOM.render(
<Icon fill="red" />,
demo
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="demo"></div>
&#13;
答案 1 :(得分:1)
对于登陆此页面的人员,还有一个Webpack加载器,可从SVG文件生成React组件。 react-svg-loader
如果您正在使用create-react-app,则可能需要暂时退出。但是知道这一点;关于在CRA和it's on the 2.0.0 roadmap apparently
中集成这样的加载器的讨论答案 2 :(得分:0)
另一种选择是不使用外部资源,而不是这样做
static public void main(String[] args) {
System.out.println(convertNumber(65));
System.out.println(convertNumber(78));
System.out.println(convertNumber(99));
System.out.println(convertNumber(901));
}
使用如下符号创建一个精灵(例如,使用https://www.npmjs.com/package/svg-sprite):
FG
IH
KK
BAK
将其内联到您的HTML中并以<use href="/path/to/icon.svg" />
样式隐藏,然后像使用它
<svg ...>
// icon contents here, except `svg` tag became `symbol` tag
<symbol id="icon-id-inside-the-sprite" ...>
// ...
</symbol>
// may be add more icons
</svg>
现在,您应该可以从外部CSS定位其内部类。
答案 3 :(得分:0)
还有一个npm软件包,可以将所有svg元素转换为正确的JSX,以防其他任何人来这里并遇到类似问题。