![](/img/trans.png)
[英]Passing props in React Route component for "react-router-dom": "^5.2.0"
[英]Pass variable on component props of Route in 'react-router-dom'
我正在使用reactjs,如何在Home組件上發送道具,它僅被稱為react-router-dom
中Route的組件參數的值,我有一個名為sample的變量,我想在內部調用它的值家庭組件類,例如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組件,並用它交換出本地路由。
<CustomRoute path="/home" component={Home} sample={sample}/>
在您的情況下,我將使其保持簡單:
<Route path="/home" render={ () => <Home sample={ sample && sample }/> } /> // sample && sample checks that the variable is not undefined
我想說這是首選方法,如果您只想傳遞一個或幾個道具。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.