我正在尝试从子组件访问 match
属性,但我不能,因为我发现它不再受支持。是否有替代方法,或者是否有其他方法可以从子组件访问这些参数,而无需隧道或降级 react 路由器?
import React from "react";
import './menuItem.style.scss'
import { withRouter } from "react-router";
const MenuItem = ({title, imageUrl,size,linkUrl, match}) => (
// console.log(match),
<div className={`${size} menu-item`} onClick={ ()=> window.history.push(`${match.url}${linkUrl}`)}>
<div style={{backgroundImage: `url(${imageUrl})`}} className="background-image" ></div>
<div className="content">
<h1 className="title">{title.toUpperCase()}</h1>
<span className="subtitle">Shop Now</span>
</div>
</div>
);
export default withRouter(MenuItem);
最佳答案
您似乎在问如何访问 react-router@6
中当前匹配的网址。 V6 不导出 withRouter
HOC,但由于您使用的是 React 函数组件,因此您不需要它,因为它可以导入和使用 RRD React hooks。
RRDv6 也不需要知道完整匹配的 URL,因为它可以使用相对路径进行导航。相对路径和绝对路径之间的区别是前导“/”字符。以 "/"
开头的目标路径被视为绝对路径,不带则被视为相对路径。
您可以导入 useNavigate
Hook 并从当前位置发出相对导航。
示例:
import React from "react";
import './menuItem.style.scss';
import { useNavigate } from "react-router";
const MenuItem = ({ title, imageUrl, size, linkUrl }) => {
const navigate = useNavigate();
return (
<div
className={`${size} menu-item`}
onClick={() => navigate(linkUrl)}
>
<div
style={{ backgroundImage: `url(${imageUrl})` }}
className="background-image"
/>
<div className="content">
<h1 className="title">{title.toUpperCase()}</h1>
<span className="subtitle">Shop Now</span>
</div>
</div>
);
};
export default MenuItem;
如果您仍在使用需要访问旧的“route props”的类组件,那么您需要推出自己的 withRouter
HOC。
示例:
import { useParams, /* ...other hooks */ } from 'react-router-dom';
const withRouter = WrappedComponent => props => {
const params = useParams();
// ...other hooks
return (
<WrappedComponent
{...props}
{...{ params, /* other hook props */ }}
/>
);
};
export default withRouter;
关于reactjs - 有没有来自react-router的withRouter的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72735944/