如何在 ReactJS 中向 Iframe 添加标头参数

Sun*_*Sun 7 javascript iframe reactjs

我正在尝试在我的 React 应用程序中添加 iframe 组件。但我需要向 url 添加身份验证密钥。

我是 React 新手,我正在尝试这种方式:

import React, {useEffect, useState} from 'react';

function IframeComp() {
  const [content, setContent] = useState('');


  useEffect(() => {
    // Fetch the content using the method of your choice
    const fetchedContent = '<h1>Some HTML</h1>';
    setContent(fetchedContent);
  }, []);


  return (
      <iframe sandbox id="inlineFrameExample"
              title="Inline Frame Example"
              width="300"
              height="200"
              src={content}>
      </iframe>
  );
}

export default IframeComp;
Run Code Online (Sandbox Code Playgroud)

我在 Stack Overflow 中找到了解决方案(Is it possible to add Request Headers to an iframe src request?)(https://github.com/courajs/pdf-poc/blob/master/script.js),但它不在 React 中。

我想我必须做这样的事情:

var xhr = new XMLHttpRequest();

  xhr.open('GET', url);
  xhr.onreadystatechange = handler;
  xhr.responseType = 'blob';
  headers.forEach(function(header) {
    xhr.setRequestHeader('Authorization', 'JWT eyJ0eXAiOiJK');
  });
  xhr.send();
Run Code Online (Sandbox Code Playgroud)

我走在正确的轨道上吗?