我的 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 https://codesandbox.io/s/pp3n7wnzvx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)