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

问题描述 投票:0回答:2

我正在使用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;
javascript reactjs components react-router-dom
2个回答
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组件并用它替换Home Route。

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

0
投票

在你的情况下,我会保持简单:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.