我的ReactJS组件包含一个iframe。为了响应外部页面中的事件,我需要重新加载iframe。如果用户已导航到iframe中的另一个页面,则需要将其重置为首次加载该页面时所具有的URL。该网址在中可用this.props。
我尝试使用forceUpdate()。我可以看到这导致该render方法运行,但是iframe不会重置-大概是因为React无法告诉您任何更改。
目前,我正在向iframe的查询字符串添加一些随机文本:此网址更改会强制React重新呈现iframe。但是,这感觉有点脏:iframe中的页面超出了我的控制范围,因此谁知道这个额外的querystring值可能会做什么呢?
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>
}
Run Code Online (Sandbox Code Playgroud)
(如果这有所作为,我也使用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>
}
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴作品:https : //codesandbox.io/s/pp3n7wnzvx
| 归档时间: |
|
| 查看次数: |
4689 次 |
| 最近记录: |