我只想在我的 reactjs 应用程序中渲染三个 svg 图像。我遇到了数十篇文章和帖子,但想知道在 Reactjs (2019) 中呈现 svg 的最佳/正确方法是什么???
最初我使用“object type="image/svg+xml"data{...} .... 我了解到这不是渲染 svgs 的正确方法。
然后我学习“xlink:href”=>“xlinkHref in Reactjs”是/是渲染svgs的最佳实践,但这在我的React App中不起作用。
有人可以告诉我 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
最佳答案
package.json
改 react-scripts
到 2.0.3:// ... other dependencies ...
"react-scripts": "2.0.3"
npm install
svg
作为一个组件:import React from 'react';
import { ReactComponent as YourSvg } from './YourSvg.svg';
const MyComponent = () => {
return(
<YourSvg/>
);
}
export default MyComponent ;
关于reactjs - 在 ReactJS 中包含 SVG 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55035731/