【问题标题】:Pass variable on component props of Route in 'react-router-dom'在'react-router-dom'中传递Route的组件道具上的变量
【发布时间】:2019-04-29 17:00:15
【问题描述】:

我正在使用reactjs,如何在Home组件上发送props,它仅作为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


【解决方案1】:

您可以创建一个新组件,将 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}/>

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-08-11
      • 2021-12-27
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 2022-01-12
      • 2021-07-05
      • 2021-05-07
      相关资源
      最近更新 更多