Passing props to component in React Router 4

后端 未结 6 1753
太阳男子
太阳男子 2021-02-05 06:39

I am new to react-router and I just started writing an app using react-router V4. I would like to to pass props to components rendered by and I am w

相关标签:
6条回答
  • 2021-02-05 07:18

    I'll do it like the following to improve clarity.

    const myComponent = <MyComponent myProp={myProp} {...defaultProps} />
    
    
    <Match pattern="/" component={myComponent} />
    

    By this your router code won't get messed up!.

    0 讨论(0)
  • 2021-02-05 07:19
    render() {
      return (
        <Router history={browserHistory}>
          <Switch>
            <Route path="/" 
               render={ ()  => <Header 
                 title={"I am Title"} 
                 status={"Here is my status"}
               /> }
            />
            <Route path="/audience" component={Audience}/>
            <Route path="/speaker" component={Speaker}/>
          </Switch>
        </Router>
      )
    }
    
    0 讨论(0)
  • 2021-02-05 07:32

    I'm fairly new to react-router and came across a similar issue. I've created a wrapper based on the Documentation and that seems to work.

    // Wrap Component Routes
    function RouteWrapper(props) {
      const {component: Component, ...opts } = props
    
      return (
       <Route {...opts} render={props => (
         <Component {...props} {...opts}/>
       )}/>
     )
    }
    
     <RouteWrapper path='/' exact loggedIn anotherValue='blah' component={MyComponent} />
    

    So far so good

    0 讨论(0)
  • 2021-02-05 07:37

    You must use the render prop instead of component to pass on custom props, otherwise only default Route props are passed ({match, location, history}).

    I pass my props to the Router and child components like so.

    class App extends Component {
    
      render() {
        const {another} = this.props
        return <Routes myVariable={2} myBool another={another}/>
      }
    }
    
    const Routes = (props) =>
      <Switch>
        <Route path="/public" render={ (routeProps) => 
          <Public routeProps={routeProps} {...props}/>
        }/>
        <Route path="/login" component={Login}/>
        <PrivateRoute path="/" render={ (routeProps) =>
           ...
        }/>
      </Switch>
    
    0 讨论(0)
  • 2021-02-05 07:41

    The render prop is meant for writing inline matches, so your example is the ideal way to pass extra props.

    0 讨论(0)
  • 2021-02-05 07:43

    I use render in combination with a defined method like so:

    class App extends React.Component {
      childRoute (ChildComponent, match) {
        return <ChildComponent {...this.props} {...match} />
      }
    
      render () {
        <Match pattern='/' render={this.childRoute.bind(this, MyComponent)} />
      }
    }
    
    0 讨论(0)
提交回复
热议问题