使用 ref 在 React 中获取 iframe 元素

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

我有一个包含 iframe 的组件,我想在 React 中访问它的内容,我使用 ref 来处理 iframe,如何从 iframe 获取所有锚点标签

这是我的代码:

  const GridGenerator = () => {
      const [loading, setLoading] = useState(true);
      const gridIframe = useRef(null);

  function handleIframe() {
    setLoading(false);
    const iframeItem = gridIframe.current;
    const anchors = iframeItem.contentWindow.getElementsByTagName("a");
  }

  return (
    <div>
      {loading ? <div className={styles.loader} /> : null}
      <iframe
        title="Grid Generator"
        ref={gridIframe}
        src="https://collectearth.users.earthengine.app/view/collect-earth-grid-generator"
        width="100%"
        height="1000px"
        frameBorder={0}
        onLoad={handleIframe}
      />
      <Link to={routes.HOME}>Go Back</Link>
    </div>
  );
};

所以,它运行良好,直到:

const iframeItem = gridIframe.current; 

它返回 iframe 标签,但是这条线不能很好地工作

const anchors = iframeItem.contentWindow.getElementsByTagName("a");

有什么解决办法吗?谢谢你

reactjs iframe use-ref
2个回答
1
投票

对我来说,添加到

Window
有效,而不是
Document

没有

bind()
:

function handleSubmit(e) {
    alert('yay 1!', e);
}

iframeRef.current?.contentWindow?.addEventListener('click', handleSubmit, false);

bind()

function handleSubmit2() {
    alert('yay 2!', this.ele);
}

iframeRef.current?.contentWindow?.addEventListener('click', handleSubmit2.bind({ ele: iframeRef }), false);

1
投票

您需要访问 contentWindow 的文档才能获取元素,Window 接口没有任何称为

getElementsByTagName
的方法。

所以,而不是

const anchors = iframeItem.contentWindow.getElementsByTagName("a");

你应该这样做

const anchors = iframeItem.contentWindow.document.getElementsByTagName("a");

© www.soinside.com 2019 - 2024. All rights reserved.