如何设置没有匿名函数的事件监听器? (不失去范围)

How to set up an event listener without an anonymous function? (not losing scope)

我认为这是一个非常基本的问题,但我还没有找到自己解决这个问题的方法。假设我有一个 React 文件,我在其中设置了一个监听器:

ipcRenderer.on('receiveData', function() {
  console.log("Hello World");
});

我正在监听电子发送的事件。上面的例子有效。每当触发 receiveData 事件时,我的 anonymous 函数都会记录 Hello World。现在说我在同一个 React 文件中有一个不同的函数,并且不想再触发匿名函数,而是我自己的。像这样:

myOwnFunction() {
  console.log("Hello World");
}

ipcRenderer.on('receiveData', myOwnFunction);

我已经试过了,但是没有用。这是全部内容:

import React from 'react';
//...
class TextView extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
                    inputField: '',
                  };
  }

  onFormSubmit(e) {
  }
  handleInputChange(e) {
    this.setState({inputField: e.target.value})
  }


  myOwnFunction() {
    console.log("MY OWN");
  }

  onButtonClick(event) {
    ipcRenderer.send('sendInvite', 1);
    ipcRenderer.on('rightPressed', function(event, arg){ console.log("stuff"+arg); });  //line 34; this works
    ipcRenderer.on('rightPressed', myOwnFunction); //line 35, this does not work

  render() {
    return (
        <div>
        //....
        </div>
      );
  }
}

当事件发出时,我现在得到错误:

Uncaught ReferenceError: myOwnFunction is not defined at onButtonClick (file:///Users/user/Coding/electron-noprebuilt/public/js/bundle.js:1286:38) at Object.ReactErrorUtils.invokeGuardedCallback (file:///Users/user/Coding/electron-noprebuilt/public/js/bundle.js:15663:16) at executeDispatch (file:///Users/user/Coding/electron-noprebuilt/public/js/bundle.js:8657:21) at Object.executeDispatchesInOrder (file:///Users/user/Coding/electron-noprebuilt/public/js/bundle.js:8680:5) at executeDispatchesAndRelease (file:///Users/user/Coding/electron-noprebuilt/public/js/bundle.js:8114:22) at executeDispatchesAndReleaseTopLevel (file:///Users/user/Coding/electron-noprebuilt/public/js/bundle.js:8125:10) at Array.forEach (native) at forEachAccumulated (file:///Users/user/Coding/electron-noprebuilt/public/js/bundle.js:22170:9) at Object.processEventQueue (file:///Users/user/Coding/electron-noprebuilt/public/js/bundle.js:8330:7) at runEventQueueInBatch (file:///Users/user/Coding/electron-noprebuilt/public/js/bundle.js:15690:18)

使用arrow function 它将绑定context。要调用同一 class 中存在的任何 function,我们需要使用 this 关键字。像这样:

this.myOwnFunction() //it will call the 'myOwnFunction' function

使用arrow function这样写:

ipcRenderer.on('receiveData', () => {    //use arrow function
     this.myOwnFunction()
});

注意:上面的代码可以工作,但是确保你bind方法onButtonClick.