- 普通语法中,阻止默认行为可以通过返回false来进行:
<a href="#" onclick="console.log('The link was clicked.'); return false">
Click me
</a>
- react中必须显示的使用
preventDefault
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
-
❗️⭐️在react中,必须谨慎对待 JSX 回调函数中的
this
,在 JavaScript 中,class 的方法默认不会绑定this
。如果你忘记绑定this.handleClick
并把它传入了onClick
,当你调用这个函数的时候this
的值为undefined
这和js函数工作原理有关,
解决方法:
- 使用 class fields 正确的绑定回调函数:
handleClick = () => {
console.log('this is:', this);
}
-
在回调中使用箭头函数:
onClick={(e) => this.handleClick(e)}
-
在constructor中绑定
this.handleClick = this.handleClick.bind(this);
网友评论