具有不同内容的跨路由的公共组件

IT技术 reactjs react-router
2021-05-18 10:59:57

我有一个名为的组件Header,它存在于所有路由中,而应用程序的其余部分发生了变化。所以为了实现这一点,我的主要渲染代码看起来像这样(使用 ES6):

render(){
  return (
    <div>
      <Header></Header>
      <Router>
        <Route path="/" component={Home} />
        <Route path="/details/:id" component={Details} />
      </Router>
    </div>
  );
}

挑战在于 的内容<Header>应根据路线略有不同,例如每条路线的唯一标题。

如何做到这一点?

4个回答

感谢所有伟大的答案!还在琢磨他们。

为了混合使用另一个解决方案,我发现我实际上可以在 上放置任意属性Route,因此我添加了title

<Route title="My Title" component={App} />

我重新调整了我的路由层次结构以将标题包含在Router(在顶级Route组件中,而不是像以前那样在任何路由之外),所以我的主要渲染代码如下所示:

<Router>
  <Route component={App}>
    <Route path="/" component={Home} title="Home" />
    <Route path="/detail/:id" component={Detail} title="Details" />
  </Route>
</Router>

我的App包含标题并传递当前路线的标题:

class App extends React.Component {
  render(){
    var route = this.props.routes[this.props.routes.length - 1];
    return (
      <div>
        <Header title={route.title} />
        {this.props.children}
      </div>
    )
  }
}

但我不能说这是最好的解决方案。我确实喜欢我现在可以title在每条路线上放置,但我担心耦合以及我必须从routes数组中提取属性的方式

这是通量的一个很好的用例。您有在挂载时创建操作的路由处理程序。此操作进入 HeaderStore。Header 组件侦听 Header 存储并根据它进行渲染。

你可以在这里看到一个例子:

我这样做的方式(我很确定有更好的方法,但这可能会对您有所帮助)如下所示:

索引.js

// define routes
const routes = (
  <Route component={App} path="/">
    <IndexRoute component={Home} />
    <Route path="/" component={Home} />
    <Route path="/details/:id" component={Details} />
  </Route>
);

ReactDOM.render(<Router>{routes}</Router>, document.getElementById('your_id'));

应用程序.js

render() {
    return (
       <div>
        <Header routerProps={this.props.children} />
        {this.props.children}
      </div>
    );
  }

头文件.js

componentWillReceiveProps(nextProps) {
    // Get access to the pathname, it contains a string like "/details/"
    console.log(nextProps.routerProps.props.location.pathname);
}

而不是将标题放在那里......将标题放在布局组件中。每个视图都应该使用布局组件,你可以传递任何你想要的标题。

export class Layout extends React.Component{
    render() {
        return <div>
            <Header title={this.props.title} />
            {this.props.children}
        </div>
    }
}

您的所有视图都可以像这样使用相同的组件

export class SomeComponent extends React.Component{
    render() {
        return <Layout title="Some Component Title">
            <div>my elements here</div>
        </Layout>
    }
}

注意:使用这样的东西的美妙之处在于,您可以设置任何其他默认消息,例如,假设您想要显示一条 Flash 消息……有人点击某物,您想要一条消息说“你已经注册成功!(在本例中)。您可以在布局中包含您的 flash 消息,并简单地调度一个事件来显示消息。这也可以使用模态来完成,无论您的应用程序要求是什么:)