与FlowRouter反应:如何根据路径显示/隐藏组件

时间:2016-12-29 17:42:18

标签: reactjs flow-router

我有一个Meteor应用,我正在使用React进行开发,并使用FlowRouter进行路由。我项目的主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

如果路线是<Footer />,我有办法隐藏/chatroom/<anything>组件吗?

2 个答案:

答案 0 :(得分:5)

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

如果在<anything>之后/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>部分很重要和/或您有其他以聊天室开头的路线,您可以先使用

获取路线的参数
const param = FlowRouter.getParam('someParam');

然后通过检查当前路径是否包含聊天室/: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>
            )
        }
    }

答案 1 :(得分:0)

您还可以使用以下语法。它完成了与Cagri Yardimci提供的第一个例子相同的事情。

{ !currentPath.includes('chatroom') && <Footer /> }
相关问题