【发布时间】:2018-07-27 13:43:39
【问题描述】:
我的 ReactJS 组件包含一个 iframe。为了响应外部页面中的事件,我需要重新加载 iframe。如果用户导航到 iframe 中的另一个页面,我需要将其重置为我第一次加载页面时的 URL。此 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,如果这有什么不同的话。)
【问题讨论】: