如何遍历组件内的所有 img 标记

How to loop through all img tags inside a component?

本文关键字:img 标记 组件 何遍历 遍历      更新时间:2023-09-26

我正在尝试找出一种方法,允许我对组件内的所有img标签执行forEach循环。我研究了findDOMNode,但我相信它仅用于选择反应组件?

如果您有深度嵌套的子项,这可能会很棘手,但这里有一些提示:

render() {
  return (
    {/* add a ref to root node */}
    <div ref="RootNode">
      <p></p>
      <span></span>
      <img />
      <img />
      ...
    </div>
  );
}

然后以这种方式访问元素子元素:

this.refs.RootNode.children

React 提供了一个 API,它有助于循环访问这里的子元素,如 React.Children.mapReact.Children.forEach