我的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,如果这有所不同的话。)
<iframe src={this.props.myUrl}>
。 - teedyaykey
,认为这不是 React 的纯粹使用方式。然而他们的解决方案是调用forceUpdate()
,但这并不起作用;更改key
的值确实有效,因此我会采用这种方法。谢谢! :) - teedyay