如何使用ReactJS重新加载iframe?

tee*_*yay 5 iframe reactjs

我的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。)

Dio*_*llo 6

我将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

  • [Reading around](/sf/ask/2143822131/),人们似乎不赞成以这种方式使用`key`,说这不是使用React的纯粹方式。然而,他们的解决方案是调用 `forceUpdate()`,这是行不通的;改变`key` 的值_确实_有效,所以我要这样做。谢谢!:) (3认同)