我有个小问题.从服务请求数据后,我得到了一个iframe代码作为响应.

<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>

我想把它作为props 传递给我的模态组件并显示它,但当我在渲染函数中简单地将其设置为{this.props.iframe}时,它显然是将其显示为字符串.

What is the best way to display it as html in react or using JSX?

推荐答案

你可以使用财产dangerouslySetInnerHTML,就像这样

const Component = React.createClass({
  iframe: function () {
    return {
      __html: this.props.iframe
    }
  },

  render: function() {
    return (
      <div>
        <div dangerouslySetInnerHTML={ this.iframe() } />
      </div>
    );
  }
});

const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; 

ReactDOM.render(
  <Component iframe={iframe} />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

此外,您可以从包含<iframe>个标记的string(based on the question, you get iframe as a string from a server)中复制所有属性,并将其传递给新的<iframe>标记,如下所示

/**
 * getAttrs
 * returns all attributes from TAG string
 * @return Object
 */
const getAttrs = (iframeTag) => {
  var doc = document.createElement('div');
  doc.innerHTML = iframeTag;

  const iframe = doc.getElementsByTagName('iframe')[0];
  return [].slice
    .call(iframe.attributes)
    .reduce((attrs, element) => {
      attrs[element.name] = element.value;
      return attrs;
    }, {});
}

const Component = React.createClass({
  render: function() {
    return (
      <div>
        <iframe {...getAttrs(this.props.iframe) } />
      </div>
    );
  }
});

const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; 

ReactDOM.render(
  <Component iframe={iframe} />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"><div>

Reactjs相关问答推荐

如何使用mui为可重复使用的react 按钮应用不同的风格

我想将状态设置为true,直到每一张卡片都生成并在多姆中呈现

无法使用#13;或br将新行设置为文本区域'"&"<>

Reaction-路由v6动态路径RegExp

react -在选项中 Select 我想要显示和图像.但当我 Select 该选项时,我希望控件仅显示该选项的文本部分

有没有办法将MUI网格元素与Flex-Start对齐?

如何使用皮金贴图在Reactjs中制作 map 上的点之间的线的动画?

React Router:在没有手动页面刷新的情况下,路由不会更新内容

关于forwardRef,我可以';我不理解第二个用例

如何使用 App Router 和服务器组件在 Next.js 13 中实现分页

useEffect 内的 onClick 和 addEventListener 之间的 click 事件顺序差异

REACT: UseState 没有更新变量(ant design 模态形式)

使用reactrouterdom时显示"对象无效作为React子组件"错误

如何修改 react/jsx-no-useless-fragment 规则以允许 <>{children}

React - 拖放 UML

React v6 中的公共和私有路由

ReactJS 动态禁用按钮

使用 useRef(uuid()) 的目的是什么?

React - useParams() 不会失败 null / undefined 判断

React中`onScroll`和`onScrollCapture`之间的区别?