简体   繁体   中英

Can't bind React element to event listener

I have this code (edited down to the relevant part):

main.js

import { mouseDownEvent } from '../common';

export default class MyComponent extends React.Component {
  componentDidMount() {
    this.refs.btn.addEventListener(
      'mousedown',
      mouseDownEvent.bind(this) // <-- not working!
    );
  }
  render() {
    return (
      <div ref="btn" className="btn"/>
    );
  }
}

common.js:

export const mouseDownEvent = event => {
  console.log(this); // <-- 'undefined'
}

However, this inside of mouseDownEvent in common.js is undefined . Why?

Your problem is that you're using an arrow function:

export const mouseDownEvent = event => {
  console.log(this); // <-- 'undefined'
};

This causes mouseDownEvent to not get its own dynamic this ; it uses the this from the lexical outer scope. You should instead use function :

export function mouseDownEvent (event) {
    console.log(this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM