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

时间:2019-04-29 17:00:16

标签: javascript reactjs components react-router-dom

我正在使用reactjs,如何在Home组件上发送道具,该组件仅在react-router-dom中作为Route的组件参数的值调用,我有一个名为sample的变量,我想调用它在home组件类中很有价值,例如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;

2 个答案:

答案 0 :(得分:2)

您可以创建一个新组件,该组件将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组件,并用它替换出本地路由。

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

答案 1 :(得分:0)

在您的情况下,我将使其保持简单:

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

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