Mik*_*sso 4 javascript svg reactjs
我正在解决一个需要将 SVG 图像从 URL(AWS S3) 加载到 React 组件的问题。我能够使用本地文件中的 SVG 内联反应组件成功显示和加载图像。但是,svg 文件需要从 S3 存储桶内联加载,JS svg 导入不适用于 URL。
所以我试图为此找到最好的替代解决方案?
小智 10
您应该获取 svg 图像并将其粘贴到 html 中
const SVG_URL = url = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/tiger.svg';
class Svg extends React.Component {
state = {
svg: null,
loading: false,
}
componentDidMount() {
fetch(this.props.url)
.then(res => res.text())
.then(text => this.setState({ svg: text }));
}
render() {
const { loading, svg } = this.state;
if (loading) {
return <div className="spinner"/>;
} else if(!svg) {
return <div className="error"/>
}
return <div dangerouslySetInnerHTML={{ __html: this.state.svg}}/>;
}
}
ReactDOM.render(
<Svg url='https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/tiger.svg' />,
document.querySelector("#app")
);
Run Code Online (Sandbox Code Playgroud)
您可以在此处编辑示例https://jsfiddle.net/anu6x3bk/
React 不推荐使用,dangerouslySetInnerHTML所以你应该使用一些像svg-inline-react
Pet*_*lka 10
@ivnkld 的回答为我指明了正确的方向,谢谢!对于像我这样的 Google 员工,这里是使用钩子实现相同方法的:
import React, { useEffect, useState } from 'react';
const SvgInline = props => {
const [svg, setSvg] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [isErrored, setIsErrored] = useState(false);
useEffect(() => {
fetch(props.url)
.then(res => res.text())
.then(setSvg)
.catch(setIsErrored)
.then(() => setIsLoaded(true))
}, [props.url]);
return (
<div
className={`svgInline svgInline--${isLoaded ? 'loaded' : 'loading'} ${isErrored ? 'svgInline--errored' : ''}`}
dangerouslySetInnerHTML={{ __html: svg }}
/>
);
}
Run Code Online (Sandbox Code Playgroud)