Search code examples
javascriptreactjsecmascript-6flux

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?


Solution

  • 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);
    }