Passing props to React Router children routes

后端 未结 3 903
时光说笑
时光说笑 2020-12-08 20:27

I\'m having trouble overcoming an issue with react router. The scenario is that i need to pass children routes a set of props from a state parent component and route.
wh

3条回答
  •  无人及你
    2020-12-08 20:47

    I ran into a similar issue and discovered that you can access props set on the Route through this.props.route in your route component. Knowing this, I organized my components like this:

    index.js

    React.render((
      
        
            
        
      
    ), document.getElementById('app'));
    

    App.js

    class App extends React.Component {
      constructor(props) {
        super(props);
      }
    
      render() {
        return 
    {this.props.children}
    ; } }

    HelloView.js

    class HelloView extends React.Component {
      constructor(props) {
        super(props);
      }
    
      render() {
        return 
      {this.props.route.fruits.map(fruit =>
    • {fruit}
    • )}
    ; } }

    This is using react-router v1.0-beta3. Hope this helps!


    Ok, now that I'm understanding your issue better, here's what you could try.

    Since your child props are coming from a single parent, your parent component, not react-router, should be the one managing which child gets rendered so that you can control which props are passed.

    You could try changing your route to use a param, then inspect that param in your parent component to render the appropriate child component.

    Route

    
    

    Parent Component

    render: function () {
      if (this.props.params.name === 'price') {
        return 
      } else if (this.props.params.name === 'time') {
        return 
      } else {
        // something else
      }
    }
    

提交回复
热议问题