首页 > 解决方案 > React-Router 和 iFrame

问题描述

当从 iFrame 调用 ReactJS 应用程序时,是否可以在 React-Router 中执行一些规则以仅显示某些路由?

我有以下路线,如您所见,它们将始终显示<Header /><Footer />组件:

...
<Route component={Header} />
<Route exact path="/" component={Landing} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={Footer} />
...

但是,当有人从 iFrame 将我的应用程序嵌入到他的网站(如小部件)中时,我不想显示<Header /><Footer />组件,所以它的行为如下:

...
<Route exact path="/" component={Landing} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
...

标签: reactjsreact-router-v4

解决方案


维护状态或道具是否嵌入 iframe。我在以下示例中使用了道具:

render() {
        return (
            <div>
                {this.props.inIframe !== null && this.props.inInframe !== true ? <Header /> : null}
                <Switch>
                    <Route exact path="/" component={Dashboard}/>
                    <Route path="/about" component={WebsiteEditor}/>
                    <Route path="/contact" component={WebsiteViewer} />
                </Switch>
                {this.props.inIframe !== null && this.props.inInframe !== true ? <Footer /> : null}
            </div>
        );
    }

推荐阅读