【问题标题】:Can't bind React element to event listener无法将 React 元素绑定到事件侦听器
【发布时间】:2015-11-24 06:18:17
【问题描述】:

我有这段代码(已编辑到相关部分):

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'
}

但是,common.js 中的mouseDownEvent 内部的thisundefined。为什么?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 flux


    【解决方案1】:

    您的问题是您使用的是箭头函数:

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

    这会导致mouseDownEvent 无法获得自己的动态this;它使用来自词汇外部范围的this。你应该改用function:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      • 2017-11-10
      • 2023-01-19
      • 2021-09-28
      相关资源
      最近更新 更多