React与FlowRouter:如何根据路由显示/隐藏组件

4

我正在使用 ReactFlowRouter 开发一个 Meteor 应用程序。我的主要 AppContainer 包含许多组件,其中之一是页脚。

class AppContainer extends Component {
    render() {
        return(
            <div className="hold-transition skin-green sidebar-mini">
                <div className="wrapper">
                    <Header user={this.props.user} />
                    <MainSideBar />
                    {this.props.content}
                    <Footer />
                    <ControlSideBar />
                    <div className="control-sidebar-bg"></div>
                </div>
            </div>
        )
    }
}

我有几个路由可以进入不同的聊天室:

例如:

/chatroom/1
/chatroom/2
/chatroom/3

如果路由是/chatroom/<anything>,有没有办法隐藏<Footer />组件?

2个回答

8

您可以通过检查当前路径来进行条件渲染。

如果 <anything> 部分(我假设它是一个参数)在 /chatroom/ 后面并不重要,而且如果您没有任何其他以 chatroom 开头的路由,您可以尝试这个:

 const currentPath = window.location.pathname
{!currentPath.includes('chatroom') ? <Footer /> : null }

因此,您的代码将如下所示:
class AppContainer extends Component {
    render() {
       currentPath = window.location.pathname
        return(
            <div className="hold-transition skin-green sidebar-mini">
                <div className="wrapper">
                    <Header user={this.props.user} />
                    <MainSideBar />
                    {this.props.content}
                    {!currentPath.includes('chatroom')
                    ? <Footer /> 
                    : null }
                    <ControlSideBar />
                    <div className="control-sidebar-bg"></div>
                </div>
            </div>
        )
    }
}

如果<anything>部分很重要且/或您还有其他以chatroom开头的路由,您可以首先使用以下方法获取该路由的参数:
const param = FlowRouter.getParam('someParam');

然后,通过检查当前路径是否包含chatroom/:param来进行条件呈现,就像这样:

  const currentPath = window.location.pathname
{!currentPath.includes(`chatroom/${param}`) ? <Footer /> : null }

那么你的代码应该长这样

 class AppContainer extends Component {
        render() {
           const currentPath = window.location.pathname
           const param = FlowRouter.getParam('someParam');
            return(
                <div className="hold-transition skin-green sidebar-mini">
                    <div className="wrapper">
                        <Header user={this.props.user} />
                        <MainSideBar />
                        {this.props.content}    
                        {!currenPath.includes(`chatroom/${param}`)
                        ? <Footer /> 
                        : null }
                        <ControlSideBar />
                        <div className="control-sidebar-bg"></div>
                    </div>
                </div>
            )
        }
    }

0

你也可以使用下面的语法。它与Cagri Yardimci提供的第一个示例完成的功能相同。

{ !currentPath.includes('chatroom') && <Footer /> }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接