美文网首页
react 事件处理

react 事件处理

作者: 糕糕AA | 来源:发表于2019-10-18 17:24 被阅读0次
    • 普通语法中,阻止默认行为可以通过返回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函数工作原理有关

      解决方法:

      1. 使用 class fields 正确的绑定回调函数:
     handleClick = () => {
        console.log('this is:', this);
     }
    
    
    1. 在回调中使用箭头函数:onClick={(e) => this.handleClick(e)}

    2. 在constructor中绑定 this.handleClick = this.handleClick.bind(this);

    相关文章

      网友评论

          本文标题:react 事件处理

          本文链接:https://www.haomeiwen.com/subject/dzhwmctx.html