简体   繁体   中英

How to display an svg image to img tag's onerror property with Typescript?

I have an image that display a jpg, but when there is an error, it shall display an svg image. However, Typescript claims onerror property only accept string. Is there a way to display an svg or a component instead with the onerror img property?

Here is my code:

 <img width="100px" height="100px" src="myimg.jpg" onError={(e) => {(e.target as HTMLImageElement).src ="error.jpg"}} /> // And with the svg: <img width="100px" height="100px" src="myimg.jpg" onError={(e) => {(e.target as HTMLImageElement).src =<Icon src="error"/>}} />

I am using React + Typescript.

You can import svg as import svgImage from '../../mysvg.svg' , this works as src of img tag. You can also import same svg as react component using import {ReactComponent as SvgImage} from '../../mysvg.svg' which can be mounted as <SvgImage/> . For your use case, you might want to import using first method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM