使用 ref 获取 React 中的 iframe 元素

2023-12-24

我有一个包含 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");

有什么解决办法吗?谢谢


对我来说添加到Window工作,而不是Document:

Without bind():

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

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

With bind():

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

iframeRef.current?.contentWindow?.addEventListener('click', handleSubmit2.bind({ ele: iframeRef }), false);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ref 获取 React 中的 iframe 元素 的相关文章

随机推荐