【发布时间】:2019-07-28 20:43:56
【问题描述】:
我只想在我的 reactjs 应用程序中渲染三个 svg 图像。我遇到过数十篇文章和帖子,但想知道在 Reactjs (2019) 中呈现 svg 的最佳/正确方法是什么???
最初我使用的是“object type="image/svg+xml" data{...} .... 我了解到这不是渲染 svgs 的正确方法。
然后我了解到 "xlink:href" => "xlinkHref in Reactjs" 是渲染 svgs 的最佳实践,但这在我的 React 应用程序中不起作用。
有人可以告诉我 xlinkHref 是否是在 Reactjs (2019) 中呈现 svgs 的正确方法吗?如果没有,可以请一些人指出方向吗?
编辑:使用解决方案更新。
import React, {Component} from 'react';
import {Link} from 'react-router-dom';
import Icon from './SvgIcons';
class PrimaryFourCol extends Component {
render() {
return (
<div className="full-width-row home-primary-bg">
<div className="row-container">
<h1 className="h1-header text-center lrg-btn-sp">My Skillset</h1>
<div className="four-col-primary__container">
<div className="four-col-primary__container__item">
<Icon name="coffee" className="our-col-primary__container__item__icon" />
<h3 className="four-col-primary__container__item__header">
Front End Development
</h3>
<p className="four-col-primary__container__item__para">
Making things look good online is my specialty
</p>
</div>
<div className="four-col-primary__container__item">
<Icon name="stats" className="our-col-primary__container__item__icon" />
<h3 className="four-col-primary__container__item__header">
Back End Development
</h3>
<p className="four-col-primary__container__item__para">
Powering applications with server-side logic
</p>
</div>
<div className="four-col-primary__container__item">
<Icon name="cartrun" className="our-col-primary__container__item__icon" />
<h3 className="four-col-primary__container__item__header">
Digital Marketing & E-Commerce
</h3>
<p className="four-col-primary__container__item__para">
Social Media, YouTube and More
</p>
</div>
</div>
<div className="text-center">
<Link to="/skills" className="btn btn--blue">My Tool kit</Link>
</div>
</div>
</div>
);
}
}
export default PrimaryFourCol;
// SvgIcons.js
import React from 'react';
import icon from '../../images/sprite.svg';
const Icon = props => {
return (
<svg xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
className={`icon icon-${props.name}`}>
<use xlinkHref={`${icon}#icon-${props.name}`}/>
</svg>
)
};
export default Icon
【问题讨论】:
-
github.com/smooth-code/svgr 。这个库附带 create-react-app 以防你的应用程序是用它制作的。否则按照 svgr repo 中的说明进行操作
-
请不要用答案更新问题 - 改为发布答案。