如何获取 React 组件的子元素?

问题描述 投票:0回答:2

我有一个像这样的

BillBoard
组件:

const BillBoard = ({ children }) => {

return (
    <>
      <h2>Billboard</h2>
      <div className="BillBoard__frame">{children}</div>
    </>
  )
}

我将一些元素放入

BillBoard
组件中,如下所示:

<BillBoard>
    <video
      width="400">
      <source
        src="/videos/BigBuckBunnySample2.mp4"
        type="video/mp4"
      />
    </video>
    <img
      width="400"
      src="/images/fabien-bellanger-zKFoVBS_WGE-unsplash.jpg"
      alt="Sea view"
    />
    <p>Some random text that appears in a slide of the billboard</p>
  </BillBoard>

如何立即获取

BillBoard
组件内的元素(在本例中为
video
元素、
img
元素和
p
元素),以便我可以在
div.BillBoard__frame
div 内一一显示它们。

reactjs children
2个回答
0
投票

您可以将孩子的类型设置为孩子的数组,代码是:

 <div className="BillBoard__frame">{children.map(child=>child)}</div>

0
投票

在 React 中,您可以使用 React.Children 实用函数访问组件的各个子元素。在您的情况下,您可以使用 React.Children.map 迭代子元素并将它们渲染在 div.BillBoard__frame 内。

你可以参考这个

以下是实现此目标的方法:

import React from 'react';

const BillBoard = ({ children }) => {
  return (
    <>
      <h2>Billboard</h2>
      <div className="BillBoard__frame">
        {React.Children.map(children, (child, index) => (
          <div key={index} className="BillBoard__item">
            {child}
          </div>
        ))}
      </div>
    </>
  );
};

const RenderComponent = () => {
  return (
    <BillBoard>
      <video width="400">
        <source src="/videos/BigBuckBunnySample2.mp4" type="video/mp4" />
      </video>
      <img
        width="400"
        src="/images/fabien-bellanger-zKFoVBS_WGE-unsplash.jpg"
        alt="Sea view"
      />
      <p>Some random text that appears in a slide of the billboard</p>
    </BillBoard>
  );
};

export default RenderComponent;
© www.soinside.com 2019 - 2024. All rights reserved.