创建历史记录返回链接并利用我现有的链接组件
我有一定的通用链接组件(一个原子,我正在使用原子设计来构建我的react应用程序),它要么只返回带有标题和箭头图标的< span>
url
它返回一个react-router-dom < link>
。
我正在使用React-Router-Dom V5。
import React from 'react';
import { Link } from 'react-router-dom';
import { Arrow} from 'app/icons';
import { Props } from './MyLink.types';
const MyLink = ({ variant = 'iconRight', text, url }: Props) => {
const renderLinkBody = () => {
return (
<React.Fragment>
<span css={styles.label}>{text}</span>
<Arrow />
</React.Fragment>
);
};
return url !== undefined ? (
<Link to={url} title={text} >
{renderLinkBody()}
</Link>
) : (
<span>{renderLinkBody()}</span>
);
};
export default MyLink;
现在,我想使用此组件来创建一个返回按钮(类似于浏览器返回按钮的行为)。
这是一种干净的方法,将OnClick Prop(功能)从父母到孩子,
const history = useHistory();
<MyLink text="My title" variant="iconLeft" onClick={history.goBack} />
然后将MyLink组件调整一点:
return url !== undefined || onClick ? (
<Link to={url} title={text} onClick={onClick} >
{renderLinkBody()}
</Link>
) : (
<span>{renderLinkBody()}</span>
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这种方法还不错。将
onclick
处理程序附加到链接
组件时,您可能需要防止默认链接行为发生。使用单击处理程序时,您还需要将有效的向
prop提供给链接
组件。示例:
由于
onclick
和link
操作的问题,并且重构myLink
根据需求有条件地渲染按钮,链接或跨度。I think this approach isn't bad. When attaching an
onClick
handler to theLink
component you will likely need to prevent the default link behavior from occurring. You will also need to provide a validto
prop to theLink
component when using a click handler.Example:
Because of the issue with the
onClick
and theLink
action, you may want to make the "back" navigation a button instead, and refactorMyLink
to conditionally render the button, the link, or the span, depending on needs.