跨越不同内容的路线的通用组件

时间:2015-11-11 06:41:08

标签: reactjs react-router

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

Header

挑战在于render(){ return ( <div> <Header></Header> <Router> <Route path="/" component={Home} /> <Route path="/details/:id" component={Details} /> </Router> </div> ); } 的内容应根据路线略有不同,例如每条路线的唯一标题。

如何实现这一目标?

4 个答案:

答案 0 :(得分:1)

这是助焊剂的一个很好的用例。您有路由处理程序在安装时创建操作。此操作进入HeaderStore。 Header组件侦听Header存储并基于它进行渲染。

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

答案 1 :(得分:1)

感谢所有出色的答案!仍然在考虑他们。

为了将另一个解决方案添加到混合中,我发现我实际上可以在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数组中提取属性的方式。

答案 2 :(得分:0)

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

<强> index.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'));

<强> App.js

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

<强> Header.js

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

答案 3 :(得分:0)

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

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消息,只需调度事件即可显示消息。这也可以通过模态完成,无论您的应用程序要求是什么:)