gpt4 book ai didi

reactjs - 如何让 withRouter 将匹配参数传递给组件?

转载 作者:行者123 更新时间:2023-12-03 13:43:04 25 4
gpt4 key购买 nike

我想访问应用程序导航上的匹配参数,我使用的是 reactreact-router-dom。这是我制作的简单示例的代码片段,正如您在 Topics 组件上看到的那样,我在组件级别获得了正确的匹配,但在导航栏中却没有,我确实在 location 属性中获得了正确的 url 路径,所以我没有确定我这样做是否正确。

This would be the working snippet ,因为我无法将 react-router-dom 添加到堆栈溢出片段。

import { BrowserRouter as Router, Route, Link, withRouter } from "react-router-dom";

const BasicExample = (props) =>
<Router>
<div>
<Nav/>
<hr />

<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>;


const About = () => (
<div>
<h2>About</h2>
</div>
);

const Home = () => (
<div>
<h2>Home</h2>
</div>
);

const Navigation = (props) => (
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
<li>{`match prop -> ${JSON.stringify(props.match)}`}</li>
<li>{`location prop -> ${JSON.stringify(props.location)}`}</li>
</ul>
);

const Nav = withRouter(Navigation);

const Topic = ({ match, location }) => (
<div>
<h3>{match.params.topicId}</h3>
<li>{`match prop -> ${JSON.stringify(match)}`}</li>
<li>{`location prop -> ${JSON.stringify(location)}`}</li>
</div>
);

const Topics = ({ match, location, history }) => (
<div>
<h2>Topics</h2>
<li>{`match prop -> ${JSON.stringify(match)}`}</li>
<li>{`location prop -> ${JSON.stringify(location)}`}</li>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>

<Route path={`${match.url}/:topicId`} component={Topic} />
<Route
exact
path={match.url}
render={() => <h3>Please select a topic.</h3>}
/>
</div>
);


ReactDOM.render(<BasicExample />, document.getElementById("root"));
<body>
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</body>

最佳答案

用于检测:topicId<Nav>使用matchPathreact-router进口:

import { matchPath } from 'react-router'

matchPath(location.pathname, {
path:'/topics/:topicId',
exact: true,
strict: false
}})

关于reactjs - 如何让 withRouter 将匹配参数传递给组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45734846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com