-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第 85 题:react-router 里的 <Link> 标签和 <a> 标签有什么区别 #135
Comments
<Link>
标签和 <a>
标签有什么区别,如何禁掉 <a>
标签默认事件,禁掉之后如何实现跳转。
从最终渲染的 DOM 来看,这两者都是链接,都是 |
先看Link点击事件handleClick部分源码 if (_this.props.onClick) _this.props.onClick(event);
if (!event.defaultPrevented && // onClick prevented default
event.button === 0 && // ignore everything but left clicks
!_this.props.target && // let browser handle "target=_blank" etc.
!isModifiedEvent(event) // ignore clicks with modifier keys
) {
event.preventDefault();
var history = _this.context.router.history;
var _this$props = _this.props,
replace = _this$props.replace,
to = _this$props.to;
if (replace) {
history.replace(to);
} else {
history.push(to);
}
} Link做了3件事情:
|
|
Link 的本质也是a 标签。只不过在Link 中禁用了 a 标签的默认事件,改用了history对象提供的方法进行跳转。 |
|
link会根据HASH的形态不同自动调整 |
history 跟 hash 模式混为一谈了吧... |
之前遇到过一个bug, 在一个SPA里点击一个链接按钮后,redux里的数据都丢了。后来才发现,不知道谁写了一个a,没有用Link。相当于重新打开了一个SPA。 |
你说的对,这才是最大的区别 |
|
<a onClick={ev=>{
ev.stopPropagation();
history.pushState(null,null,"/home");
}}>click me</a>
|
如何禁掉
<a>
标签默认事件,禁掉之后如何实现跳转The text was updated successfully, but these errors were encountered: