简体   繁体   中英

Pass variable on component props of Route in 'react-router-dom'

I'm using reactjs, How can I send props on the Home component, which is only called as a value of component parameter of Route in react-router-dom , I have a variable named sample, and I want to call it's value inside home component class, like const sample = this.props.sample how can I do that in this case?

import React, { Component } from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import ReactDOM from 'react-dom';

import Login from './components/Login';
import Home from './components/Home';
const sample = 'send this to home component';

class App extends Component {
  render() {
    return (
      <Router history={history}>
        <Switch>
          <div>
            <Route exact path="/" component={Login} /> 
            <Route path="/login" component={Login} />
            <Route path="/home" component={Home} />
          </div>
        </Switch>
      </Router>
    );
  }
}

export default App;

You can create a new component that combines react-router-doms Routes and some of your own logic.

import React from "react"
import { Route, Redirect } from "react-router-dom"

const CustomRoute = ({ component: Component, sample, ...rest}) => {
    return(
        <Route 
            {...rest}
            //route has a render prop that lets you create a component in-line with the route
            render = {props =>
                sample === true ? (
                    <Component {...props} />
                ) : (
                    <Redirect to="/login"/>
                )
            }
        />
    )
}

export default CustomRoute

Then import your CustomRoute component and swap out your Home Route with it.

<CustomRoute path="/home" component={Home} sample={sample}/>

In your case I would keep it simple:

<Route path="/home" render={ () => <Home sample={ sample && sample }/> } /> // sample && sample checks that the variable is not undefined

I would say this is the preferred method if you are looking to just pass in one or a few props.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM