반응 구성요소의 iframe 내용 설정 방법
React 컴포넌트에서 iframe의 내용을 설정하려고 하는데 설정할 수 없습니다.iframe 로드가 완료되면 호출해야 하는 함수를 포함하는 컴포넌트가 있습니다.그 기능에서 콘텐츠를 설정하고 있습니다만, 온로드 기능이 전혀 호출되지 않는 것 같습니다.Chrome 브라우저로 테스트하고 있습니다.다음을 시도하고 있습니다.
var MyIframe = React.createClass({
componentDidMount : function(){
var iframe = this.refs.iframe.getDOMNode();
if(iframe.attachEvent){
iframe.attacheEvent("onload", this.props.onLoad);
}else{
iframe.onload = this.props.onLoad;
}
},
render: function(){
return <iframe ref="iframe" {...this.props}/>;
}
});
var Display = React.createClass({
getInitialState : function(){
return {
oasData : ""
};
},
iframeOnLoad : function(){
var iframe = this.refs.bannerIframe;
iframe.contentDocument.open();
iframe.contentDocument.write(['<head></head><style>body {margin: 0; overflow: hidden;display:inline-block;} html{ margin: 0 auto; text-align: center;} body > a > img {max-width: 100%; height: inherit;}', extraCss, '</style></head><body>', this.state.oasData.Ad[0].Text, '</body>'].join(''));
iframe.contentDocument.close();
},
setOasData : function(data){
this.setState({
oasData : JSON.parse(data)
});
},
componentDidMount : function(){
var url = "getJsonDataUrl";
var xhttp = new XMLHttpRequest();
var changeOasDataFunction = this.setOasData;
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
changeOasDataFunction(xhttp.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
},
render : function(){
return (
<MyIframe refs="bannerIframe" onLoad={this.iframeOnLoad} />
);
}
});
module.exports = Display;
내가 뭘 잘못하고 있지?
TLDR;
를 이 문서의 <iframe>
사실상의 표준적인 방법으로 리액션을 통해 포털을 이용할 수 있습니다.포털의 모든 것과 마찬가지로:기존 마운트된 DOM 노드에 대한 참조를 확립하면(이 경우 지정된 창의 contentWindow가 됩니다).<iframe>
를 사용하여 포털을 만듭니다.포털의 내용은 공유(합성) 이벤트시스템, 컨텍스트 등을 의미하는 '부모' 가상 DOM의 자녀로도 간주됩니다.
코드 간결성을 위해 다음 예에서는 옵션 체인 연산자를 사용하고 있습니다.이 연산자는 현재 모든 브라우저에서 지원되지 않습니다.
예: 후크를 포함한 기능성 React 컴포넌트:
// iframe.js
import React, { useState } from 'react'
import { createPortal } from 'react-dom'
export const IFrame = ({
children,
...props
}) => {
const [contentRef, setContentRef] = useState(null)
const mountNode =
contentRef?.contentWindow?.document?.body
return (
<iframe {...props} ref={setContentRef}>
{mountNode && createPortal(children, mountNode)}
</iframe>
)
}
예: React 클래스 구성 요소:
// iframe.js
import React, { Component } from 'react'
import { createPortal } from 'react-dom'
export class IFrame extends Component {
constructor(props) {
super(props)
this.state = {
mountNode: null
}
this.setContentRef = (contentRef) => {
this.setState({
mountNode: contentRef?.contentWindow?.document?.body
})
}
}
render() {
const { children, ...props } = this.props
const { mountNode } = this.state
return (
<iframe
{...props}
ref={this.setContentRef}
>
{mountNode && createPortal(children, mountNode)}
</iframe>
)
}
}
사용방법:
import { IFrame } from './iframe'
const MyComp = () => (
<IFrame>
<h1>Hello Content!</h1>
</IFrame>
)
, 「」( 「」)에 추가 제어<iframe>
s <head>
콘텐츠는 이 Gist가 보여주는 것처럼 쉽게 달성할 수 있습니다.
리액트 프레임 컴포넌트도 있는데, 이 패키지는 imho가 제어된 상태로 작업할 때 필요한 거의 모든 것을 제공합니다.<iframe>
s in React.
경고:
- 사례만 으로 하고 있습니다. 사례는 특정 사용 사례의 입니다.
<iframe>
님은 리액트 방식으로 콘텐츠를 프로그래밍 방식으로 제어하려고 합니다. - 은 '의가 '아주머니'로가정하고 있습니다.
<iframe>
는 동일 발신기지 정책을 준수합니다. - 은 외부 하는 데 .
<iframe src="https://www.openpgp.org/>
시나리오 같은 거요 - 접근성에 관심이 있는 경우 iframes에 의미 있는 제목 속성을 지정해야 합니다.
(내가 알고 있는) 사용 사례
- OP의 사용 사례:광고 및 광고가 웹 사이트의 안전한 범위 요소에 액세스할 수 있는 방법과 시기를 제어할 필요성.
- 내장 가능한 서드파티 위젯입니다.
- 나의 사용 사례(따라서 이 문제에 대한 나의 어느 정도 정보에 입각한 입장:CMS UI: 적용된 미디어 쿼리를 포함하여 사용자가 범위 지정 CSS 스타일을 미리 볼 수 있도록 합니다.
스타일(를 제어된 CSS에 한다.<iframe>
:
와 같이 <iframe>
운 도 전용이 있으면 (a)에 필요한 모든 비주얼 되어 있습니다.<iframe>
할 수도 있어요.IFrame
a의<link>
에 준거한 도 해당 스타일을 <link>
삭제:
const MyComp = () => (
<Frame>
<link rel="stylesheet" href="my-bundle.css">
<h1>Hello Content!</h1>
</Frame>
)
그러나 오늘날, 특히 React 세계에서는 대부분의 경우 빌드 셋업이 스타일과 스타일시트를 즉석에서 만듭니다.SAS와 같은 메타 언어나 CSS-in-JS와 같은 보다 복잡한 솔루션(스타일 컴포넌트, 감정)을 활용하기 때문입니다.
이 샌드박스에는 React에 iframe과 함께 인기 있는 스타일링 전략을 통합하는 방법의 예가 포함되어 있습니다.
이 답변은 또한 16.3 이전 버전의 React에 대한 레시피를 제공하는 데 사용되었습니다.다만, 현시점에서는, 대부분이 Portals를 포함한 React 버전이나, 보다 적은 훅을 사용할 수 있다고 해도 무방할 것 같습니다.iframes 및 React 버전 < 16에 관한 솔루션이 필요하시면 연락주세요.자세한 내용은 이쪽에서 알려드리겠습니다.
만약 누군가가 iframe 안에 작은 HTML을 표시하기를 원한다면 더 쉬운 해결책이 있습니다.
<iframe src={"data:text/html,"+encodeURIComponent(content)}/>
콘텐츠의 최대 길이는 32768자입니다.
또한 수용된 답변에서 언급된 react-frame-component 패키지도 쉽게 사용할 수 있습니다.
하시면 됩니다.srcdoc
iframe .잘될!!
srcdoc : src Atribute를 덮어쓰는 삽입 인라인HTML.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe 확인.
이것도 동작합니다(IE에서는 지원되지 않습니다).
const myHTML = <h1>Hello World</h1>
<iframe srcDoc={myHTML} />
자세한 내용은 이쪽:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe
할 수 .ReactDOMServer.renderToString()
로 srcDoc
iframe .
import ReactDOMServer from "react-dom/server";
const MyComponent = () => {
return <h1>Hello Content!</h1>;
};
const App = () => {
const srcDoc = <MyComponent />;
return (
<iframe
title="my-iframe"
width="500px"
height="500px"
srcDoc={ReactDOMServer.renderToString(srcDoc)}
></iframe>
);
};
데모: 코드 앤 박스
DOMParser 컨스트럭터의 parseFromString을 사용하여 html을 해석하는 것은 허용된 답변보다 조금 더 간단합니다.다음은 DOMParser의 생성된 문서에서 구문 분석된 html을 검색하는 예입니다.요소를 iframe으로 송신하는 경우는,.body.innerText
의 일부parseHtml
.
class SimpleIframe extends Component {
render() {
const parseHtml = html => new DOMParser().parseFromString(html, 'text/html').body.innerText;
return <iframe srcDoc={parseHtml(this.props.wholeHTMLDocumentString)} />;
}
}
언급URL : https://stackoverflow.com/questions/34743264/how-to-set-iframe-content-of-a-react-component
'programing' 카테고리의 다른 글
Ajax 요청 내의 jQuery Ajax 요청 (0) | 2023.03.12 |
---|---|
$resource 'get' 함수는 어떻게 AngularJS에서 동기적으로 작동합니까? (0) | 2023.03.12 |
laravel - http 요청에서 매개 변수를 가져옵니다. (0) | 2023.03.12 |
JSHint(r10): 'angular'가 정의되지 않았습니다. (0) | 2023.03.12 |
스프링 보안 및 JSON 인증 (0) | 2023.03.12 |