admin管理员组

文章数量:1122832

I have created a React component that makes use of the HTML <picture> and tags. The component creates several <source> options and has a fallback <img> at the end.

React seems to know that <img> is a self-closing tag when the component is rendered but adds a closing </source> to each use of this HTML element. How would I prevent this behaviour?

In this case I have six variables that contain differently resolution of the image.

<source
   media={`(max-width: 200px)`}
   srcset={`${small_src}, ${small_src2x} 2x`}
/>
<source
   media={`(max-width: 400px)`}
   srcset={`${mid_src}, ${mid_src2x} 2x`}
/>
<img
   src={large_source}
   srcset={`${large_source}, ${large_source 2x} 2x`}
/>

This renders

<picture>
  <source 
    media="(max-width: 200px)" srcset="..pathToSmall, ..pathToSmall@2x 2x">
  </source>
  <source 
    media="(max-width: 400px)" srcset="..pathToMid, ..pathToMid@2x 2x">
  </source>
  <img
    src="..pathToLarge"
    srcset="..pathToLarge, ..pathToLarge@2x 2x">
</picture>

So, as you can see, <img> correctly renders without a closing tag but <source> adds a closing tag. How can this be changed so as to prevent the rendering of the closing </source>. Although it still works in browsers with the closing tag it is flagged by w3 validation with this closing tag in place.

w3 Validation error

<picture>
  <source media="(max-width: 200px)" srcset="pic1.jpg, [email protected] 2x"></source>
  <source media="(max-width: 400px)" srcset="pic2.jpg, [email protected] 2x"></source>
  
  <img alt="hi" src="pic2.jpg">
</picture>

// Error: Stray end tag source.

本文标签: reactjsHow can I prevent React from adding closing HTML tags for selfclosing tagsStack Overflow