在 'react-router-dom' 中传递 Route 的组件道具变量

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

我正在使用 reactjs,如何在 Home 组件上发送 props,它仅作为路由组件参数的值在 react-router-dom 中调用,我有一个名为 sample 的变量,我想要在 home 组件 class 中调用它的值,例如 const sample = this.props.sample 在这种情况下我该怎么做?

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;

你可以创建一个新的组件,结合 react-router-doms 路由和你自己的一些逻辑。

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

然后导入您的 CustomRoute 组件并用它替换您的 Home Route。

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

对于你的情况,我会保持简单:

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

如果您只想传递一个或几个道具,我会说这是首选方法。