【问题标题】:Render a specific children of a route渲染路线的特定子代
【发布时间】:2017-10-28 06:23:31
【问题描述】:

我在我的 reactjs 应用程序中使用 react 路由器。我为主页定义了一条路线。在这条路线中,我有两条子路线。看起来是这样的

<Route path='/' component={App}>
   <Route path='/login' component={LoginPage} />
   <Route path='/app' onEnter={hasAuth}>
      <IndexRoute component={NewHome}>
         <IndexRoute component={Reviews} />
         <Route path='/search' component={Search} />
      </IndexRoute>
   </Route>
</Route>

这是我的家庭组件

class NewHomePage extends Component {
    render() {
        return (
            <div className={c.container}>
                <div className="page-content-wrapper full-height">
                    {/*<!-- START PAGE CONTENT -->*/}
                    <div className="content full-height">
                        <div className="container-fluid container-fluid-media full-height no-padding">
                            <div className="row full-height no-margin">
                                <NewSidebar/>
                                {this.props.children}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

我想要什么我想将评论呈现为默认组件。但是当我点击我的个人资料照片(在标题中)时,我希望搜索组件代替评论。目前连Index route Riviews也没有显示出来

我怎样才能做到这一点?

【问题讨论】:

  • 你使用的是哪个版本的 react-router?点击头像时调用什么路由?
  • 使用 v4.您评论的第二部分是我的问题。采取特定操作时,我希望搜索组件代替评论。目前他们都没有演出。
  • App 组件中使用{this.props.children} 来做到这一点。
  • 在家庭组件中我正在这样做。为什么需要在 App 组件中做呢?
  • 在这种情况下似乎 home 组件与应用程序相同

标签: reactjs react-router


【解决方案1】:

您可以使用Switch

对于配置文件,请单击此处定义 LinkNavLink

<Link to="/profile">Profile</Link>

路由器:

<Switch>
          <Route exact path='/' component={Reviews}></Route>
          <Route path='/profile' component={Search}></Route>
</Switch>

【讨论】:

    【解决方案2】:

    要实现您想要的,您必须对您的路线进行轻微更改,如下所示:

    <Route path='/' component={App}>
        <Route path='/login' component={LoginPage} />
        <Route path='/app' onEnter={hasAuth} component={NewHome}>
          <IndexRoute component={Reviews} />
          <Route path='/search' component={Search} />
        </Route>  
    </Route>
    

    然后在您的NewHome 组件中,如果它是一个功能/无状态组件,您将使用{props.children},如果它是一个有状态组件,您将使用{this.props.children}

    功能组件的示例如下所示: 从“反应”导入反应;

    const NewHome = (props) => {
      return (
        <div>
          {props.children}
        </div>
      );
    };
    
    export default NewHome;
    

    对于有状态的组件,它看起来像这样:

    export default class NewHome extends Component {
      render() {
        return (
          <div>
            {this.props.children}
          </div>
        );
      }
    }
    

    【讨论】:

    • 我在发帖前试过这个。我的问题是当点击某个按钮时如何用搜索替换评论
    • 你可以将你的搜索变成一个模式而不是把它作为一个路线。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多