javascript - 在 javascript 中干燥 html 包装器

标签 javascript jquery html reactjs

我正在使用 React js 并正在构建大量重复元素,这些元素都包含在相同的 html 中,如下所示:

<div>
  <div class="child">
    <div class="grand-child">
      <Element1 />
    </div>
  </div>
  <div class="child">
    <div class="grand-child">
      <Element2 />
    </div>
  </div>
  <div class="child">
    <div class="grand-child">
      <Element3 />
    </div>
  </div>
</div>

我不必不断地将每个元素包装在“子”和“孙子”div 中,有没有一种更简单的方法可以编写此代码,这样我就不必重复自己了?

我研究过类似 innerHTML 属性的东西,它标记一个 html 元素并在该原始元素内插入信息/元素。我想做的是相反的,而是采用我的原始元素并将其与其他 html 元素包装起来,但似乎 outerHTML 属性不以这种方式运行。

是否有任何方法可以包装 html 元素,如下面的伪解决方案所示?谢谢。

Let <foo></foo> =
  <div class="child">
    <div class="grand-child">
    </div>
  </div>

<div class="parent">
  <foo>
    <p>This is the first element</p>
  </foo>
  <foo>
    <p>This is the second element</p>
  </foo>
  <foo>
    <p>This is the third element</p>
  </foo>
</div>

最佳答案

有几个好方法可以做到这一点:(1) 使用数组存储内容并 .mapping 到您想要的标记,以及 (2) 创建一个单独的组件包装器,将内容作为 children 传递。您甚至可以组合这些,具体取决于您希望包装器组件的可重用程度:

(1) 使用 .map,这应该会产生与第一个示例中相同的标记:

<div>
  {[Element1, Element2, Element3].map((Element, index) => (
    <div class="child" key={index}>
      <div class="grand-child">
        <Element />
      </div>
    </div>
  ))}
</div>

(2) 如果您想拆分成一个单独的组件,您可以执行以下操作,使用无状态功能性“包装器”组件和 props.children 访问传递下来的内容:

const Wrapper = props => (
  <div class="child">
    <div class="grand-child">
      {props.children}
    </div>
  </div>
)

...

<div>
  <Wrapper>
    <Element1 />
  </Wrapper>
  <Wrapper>
    <Element2 />
  </Wrapper>
  <Wrapper>
    <Element3 />
  </Wrapper>
</div>

最后,如果你想结合这些,你可以创建一个包装器组件并在 .map 调用中使用它来传递不同的内容:

const Wrapper = props => (
  <div class="child">
    <div class="grand-child">
      {props.children}
    </div>
  </div>
)

...


<div>
  {[Element1, Element2, Element3].map((Element, index) => (
    <Wrapper key={index}>
      <Element />
    </Wrapper>
  ))}
</div>

关于javascript - 在 javascript 中干燥 html 包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48647523/

相关文章:

javascript - 未调用 Angular 登录/注销功能

javascript - 如果我把它放在submitHandler中,为什么我的按钮在jquery中会点击两次?

javascript - 运行javascript修改css

jquery - Bootstrap Alpha Carousel 淡入淡出过渡

javascript - 获取示例图像中的 HTML 样式

javascript - 使用 jQuery 显示来自 JSON 的多个图像

jquery - 找到第一个选择了第一个值的选择?

javascript - 禁用按 Tab 按钮进入 Web 表单中的下一个输入字段

javascript - 调整剑道网格内的文本区域

html - 如何让 <img> 标签在 div 中水平排列?