簡體   English   中英

ReactJS 中 iFrame 的 document.getElementById

[英]document.getElementById for iFrame in ReactJS

在我的站點中,我需要將信息(通過 postMessage)發送到 iFrame。 I know in regular Javascript, I would accomplish this by using document.getElementById or $("#iframe") in JQuery to select the iframe. 但是,我不確定如何在 ReactJS 中執行此操作。 在 ReactJS/NextJS 中是否有一種我不知道的特定方法? 我需要從其容器(父組件)訪問 iframe(子組件)。

如果iframe由 React 渲染,並且只有渲染它的組件(或其后代)需要訪問它,那么通常您使用refs

如果iframe始終在頁面上,或者以某種方式在 React 之外呈現,則可以通過document.getElementByIddocument.querySelector或其他 DOM 方法獲取它。


這是通過useRef在功能組件中使用 ref 的示例,但是您可以通過createRef在 class 組件中執行相同的操作(以不同的方式)。 我將使用div代替iframe ,但iframe相同。

 function Example() { const ref = React.useRef(null); const doSomething = () => { if (ref.current) { console.log(`The div's text is "${ref.current.textContent}"`); } else { console.log("The div doesn't exist"); } }; return ( <div> <div ref={ref}> This is the target div </div> <input type="button" onClick={doSomething} value="Click Me" /> </div> ); } ReactDOM.render(<Example/>, document.getElementById("root"));
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

Class 組件示例:

 class Example extends React.Component { constructor(props) { super(props); this.ref = React.createRef(); this.doSomething = this.doSomething.bind(this); } doSomething() { if (this.ref.current) { console.log(`The div's text is "${this.ref.current.textContent}"`); } else { console.log("The div doesn't exist"); } } render() { return ( <div> <div ref={this.ref}> This is the target div </div> <input type="button" onClick={this.doSomething} value="Click Me" /> </div> ); } } ReactDOM.render(<Example/>, document.getElementById("root"));
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM