html - 我们如何通过在 ReactJs (Jsx) 中使用 <div> 来破坏 HTML 语义

标签 html reactjs

ReactJs 文档说:

Sometimes we break HTML semantics when we add <div> elements to our JSX to make our React code work, especially when working with lists (<ol>, <ul> and <dl>) and the HTML <table>. In these cases we should rather use React Fragments to group together multiple elements.

引用:https://reactjs.org/docs/accessibility.html

我真的很想知道我们如何通过使用 <div> 来打破 HTML 语义或上面提到的其他元素,以及 React Fragments 如何改进它。

此外,我想了解破坏这种语义可能会出现什么问题。

提前致谢。

最佳答案

假设您有一个

    元素,您想要在其中插入几个
  • 标签。 React 元素只能有一个根节点,所以首先想到的是将所有
  • 标签包装在一个
    中,例如以下内容:

      const element = () => {
         return (
           <div>
             <li>Some list item</li>
             <li>Some other list item</li>
           </div>
         );
      };
    
      ReactDOM.render(element, document.getElementById('root'));
    

    这将产生以下 HTML:

    <ul id="root">
        <div>
            <li>Some list item</li>
            <li>Some other list item</li>
        <div>
    </ul>
    

    现在我们成功打破了 HTML 语义,直接在 ul 元素中包含 div 是无效的 HTML。避免这种情况的一种方法是使用 React Fragments:

      const element = () => {
         return (
           <Fragment>
             <li>Some list item</li>
             <li>Some other list item</li>
           </Fragment>
         );
      };
    
      ReactDOM.render(element, document.getElementById('root'));
    

    片段不会插入不会破坏语义的额外 HTML 标记。这是生成的 HTML

    <ul id="root">
        <li>Some list item</li>
        <li>Some other list item</li>
    </ul>
    

    关于html - 我们如何通过在 ReactJs (Jsx) 中使用 <div> 来破坏 HTML 语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52943413/

相关文章:

css - 我需要将这两个 div 堆叠在一起,同时保持内容位置

javascript - 无法读取未定义的属性 '__reactAutoBindMap'

javascript - 在 reactJS 中验证复选框的简单函数

javascript - 在下一个页面 reactjs 中搜索结果

reactjs - 如何对material-ui的卡片组件进行样式设计,上面没有太多内容?

javascript - 在 JavaScript 中从 Firebase 中删除特定 Node

html - 在 Angular 模板绑定(bind)中剥离 html

html - 使div在IE6和IE7/FF中看起来一样

html - 如何从此圆形图标中删除黑色边框?

javascript - HTML - CSS - 如何在居中且可调整大小的父级中左对齐图像