Если iframe
отображается React, и только компонент, который его отображает (или его потомки), должен получить к нему доступ, то обычно вы используете refs .
Если iframe
всегда находится на странице или отображается каким-либо образом вне React, вполне нормально получить его с помощью document.getElementById
, document.querySelector
или других методов DOM.
Вот пример использования ссылки в функциональном компоненте через useRef
, но вы можете сделать то же самое (другим способом) в компоненте класса через createRef
. Я буду использовать div
вместо iframe
, но это то же самое для iframe
s.
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 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>