我有一个在路由
上加载的react组件我需要从组件构造函数
中的url访问参数我该怎么做?
我可以像这样访问它:class CustomCoponent extends React.Component {
constructor(props,{match}) {
}
}
答案 0 :(得分:4)
您可以通过react-router-dom
道具中的参数来访问v4.x
match
中的路线参数。
您定义路线的地方
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
...
<Router>
<App>
<Switch>
<Route exact path="/" component={List} />
<Route path="/:parameterToAccess" component={CustomComponent} />
</Switch>
</App>
</Router>
...
在您的组件中,
class CustomComponent extends React.Component {
constructor(props) {
super(props);
this.routeParam = props.match.params.parameterToAccess;
}
}
答案 1 :(得分:3)
如果您使用路由,那么您可以指定您期望参数的路由。
<Route path='/yourpath/:ParamName' component={CustomCoponent}/>
您的组件需要包含在withRouter HOC中,以便您访问它。
import {withRouter} from 'react-router-dom';
class CustomCoponent extends React.Component {
constructor(props) {
}
//**ACCESS PARAMETER VALUE LIKE THIS**
sample(){
let Paramvalue=this.props.match.params.ParamName;
}
}
export defualt withRouter(CustomCoponent);
答案 2 :(得分:2)
你可以这样做:
if (hasProperty('subProj')) {
include "subProj"
} else {
include "subProj1", "subProj2", "subProj3"
}
答案 3 :(得分:1)
由于{match}作为prop(property)传递到组件,因此我们可以按常规prop方式访问该prop。
class CustomComponent extends React.Component {
console.log(this.props.match.url)
}
答案 4 :(得分:0)
路线
import logo from './logo.svg';
import './App.css';
import {BrowserRouter as Router,Route,Switch} from 'react-router-dom';
import UpdateEmployeeComponent from './components/UpdateEmployeeComponent';
function App() {
return (
<div>
<Router>
<div className="container">
<Switch>
<Route path="/update-employee/:id" component={UpdateEmployeeComponent}></Route>
</Switch>
</div>
</Router>
</div>
);
}
export default App;
组件
import React, { Component } from 'react';
class UpdateEmployeeComponent extends Component {
constructor(props){
super(props);
this.state ={
id : this.props.match.params.id
}
console.log('Employee Id ::: '+this.id);
}
render() {
return (
<div>
</div>
);
}
}
export default UpdateEmployeeComponent;