React router and this.props.children - how to pass state to this.props.children

前端 未结 3 1160
醉酒成梦
醉酒成梦 2020-12-01 10:21

I\'m using React-router for the first time and I don\'t know how to think in it yet. Here\'s how i\'m loading my components in nested routes.

entry point .js

3条回答
  •  醉话见心
    2020-12-01 11:06

    There's also the option of using Context. React-Router relies on it to give access to the Router object in the route components.

    From another answer I gave on a similar question:

    I quickly put together an example using contexts on codepen. MainLayout defines some properties that could be used by the children using the context: users and widgets. These properties are used by the UserList and WidgetList components. Notice they need to define what they need to access from the context in the contextTypes object.

    var { Router, Route, IndexRoute, Link } = ReactRouter
    
    var MainLayout = React.createClass({
      childContextTypes: {
        users: React.PropTypes.array,
        widgets: React.PropTypes.array,
      },
      getChildContext: function() {
        return {
          users: ["Dan", "Ryan", "Michael"], 
          widgets: ["Widget 1", "Widget 2", "Widget 3"]
        };
      },
      render: function() {
        return (
          
    {this.props.children}
    ) } }) var Home = React.createClass({ render: function() { return (

    Home Page

    ) } }) var SearchLayout = React.createClass({ render: function() { return (
    {this.props.children}
    ) } }) var UserList = React.createClass({ contextTypes: { users: React.PropTypes.array }, render: function() { return (
      {this.context.users.map(function(user, index) { return
    • {user}
    • ; })}
    ) } }) var WidgetList = React.createClass({ contextTypes: { widgets: React.PropTypes.array }, render: function() { return (
      {this.context.widgets.map(function(widget, index) { return
    • {widget}
    • ; })}
    ) } }) var Routes = React.createClass({ render: function() { return ; } }) ReactDOM.render(, document.getElementById('root'))

提交回复
热议问题