我想在基于流星的反应项目中获取当前路径路径,我想在外部创建登录页面。我可以这样做吗? 这是我的源代码
的客户机/ main.jsx
import React from "react";
import {meteor} from "meteor/meteor";
import {render} from "react-dom";
import {
BrowserRouter as Router,
Route
} from "react-router-dom"
import "./main.css";
import "../imports/ui/stylesheets/main.scss";
import Main from "../imports/ui/Main";
Meteor.startup(() => {
return render((
<Router>
<Main/>
</Router>
), document.getElementById("app-root"));
});
UI / main.jsx
import React, {Component} from "react";
import Link, {withRouter} from "react-router-dom"
import PropTypes from "prop-types";
/*@import Templates*/
import Sidebar from "./components/sidebar";
class Main extends Component {
render() {
return (
<div className="container-fluid">
<Sidebar/>
//want current location path for here
</div>
);
}
}
export default Main;
二手版本:
答案 0 :(得分:2)
您必须将反应路由器HOC应用于您的组件(文件末尾的withRouter(Main)
),然后它会将一些道具传递给您的组件,包括match
和location
match
prop包含url
和path
以显示组件路由(path
将为您提供具有参数名称的路由,例如“user /:id”,url给你一个param变量的真实网址,例如“user / 1d6qsqsd56”)。
location.pathname
会在您调用它的地方提供实际网址(在侧边栏组件中提供“/ user / 1d6qsqsd56”)。
class Main extends Component {
render() {
return (
<div className="container-fluid">
<Sidebar/>
<p> Route path : {this.props.location.pathname} </p>
</div>
);
}
}
export default withRouter(Main);
编辑:更正了不同路由器道具的实际行为。
答案 1 :(得分:0)
您需要像这样
访问组件实例的注入属性位置let currentLocationPath = this.props.location.pathname
了解更多信息https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/location.md