我的 ReactJS 组件包含一个 iframe。为了响应外部页面中的事件,我需要重新加载 iframe。如果用户已导航到 iframe 中的另一个页面,我需要将其重置为首次加载该页面时的 URL。此网址可在
this.props
中找到。
我尝试过使用
forceUpdate()
。我可以看到这会导致 render
方法运行,但 iframe 不会重置 - 大概是因为 React 无法判断任何内容发生了变化。
目前我正在向 iframe 的查询字符串附加一些随机文本:此 URL 更改迫使 React 重新渲染 iframe。然而,这感觉有点脏:iframe 中的页面超出了我的控制范围,所以谁知道这个额外的查询字符串值可能会做什么?
resetIframe() {
console.log("==== resetIframe ====");
this.forceUpdate();
}
public render() {
console.log("==== render ====");
// How can I use just this.props.myUrl, without the Math.random()?
let iframeUrl = this.props.myUrl + '&random=' + Math.random().toString();
return <div>
<button onClick={() => { this.resetIframe(); }}>Reset</button>
<iframe src={iframeUrl}></iframe>
</div>
}
(我也在使用 TypeScript,如果这有什么不同的话。)
我会用随机数创建一个
state
变量,然后在 resetIframe
上更新它:
state = {
random: 0
}
resetIframe() {
this.setState({random: this.state.random + 1});
}
public render() {
return <div>
<button onClick={() => { this.resetIframe(); }}>Reset</button>
<iframe key={this.state.random} src={this.props.myUrl}></iframe>
</div>
}
这是一个正在工作的小提琴:https://codesandbox.io/s/pp3n7wnzvx
对于 Javascript 框架和技术,如果您更新密钥,那么它会自动重新加载 iFrame。所以你只想增加(或随机数)你的操作的键值。
state = {
iframe_key: 0,
iframe_url: 'https://www.google.com/maps' //Your URL here
}
iframeRefresh() {
this.setState({iframe_key: this.state.iframe_key + 1});
}
public render() {
return (
<div>
<button onClick={() => { this.iframeRefresh(); }}>Reload Iframe</button>
<iframe key={this.state.iframe_key} src={this.state.iframe_url}>
</iframe>
</div>
);
}
更新源会导致重新加载,但不会导致重新渲染。
import React, { useState, useRef } from 'react'
function renderIframe({src}){
const iframeRef = useRef()
return <>
<iframe ref={iframeRef} src={src} >
<span onClick={e => (iframeRef.current.src += '')}>Reload</span
</>
}
<iframe key={props.location.key} />
使用此“路由器位置键”每次点击都会获得随机值,每当导航到此处时该值都会发生变化,然后 iframe 将获得刷新
您可以创建一个仅加载 iframe 的新组件。在你的主组件中,你加载它并给它一个 update 属性,你在 iframe 组件中忽略它。如果您使用状态变量设置 prop,您的组件将重新加载。你可以看看 Diogo Sgrillo 对 setState 方法的回答。
您还可以使用 shouldcomponentupdate() 检查 prop 是否发生变化,并且仅在发生变化时更新。
这里可能有点晚了:)只是旁注:当您根据先前的状态更新状态时,您应该将一个函数传递给setState:
resetIframe() {
this.setState(prevState => {random: prevState.random + 1});
}
我认为这是更简单的方法:
const resetIframes = () => {
const iframes = document.querySelectorAll("iframe");
iframes.forEach((iframe) => {
iframe.src = iframe.src;
});
};