这是我假设的一个基本问题,但我还没有找到如何自己解决这个问题。假设我有一个React文件,我在其中设置了一个监听器:
ipcRenderer.on('receiveData', function() {
console.log("Hello World");
});
我在听电子发来的事件。上面的例子有效。每当触发receiveData事件时,我的匿名函数都会记录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>
);
}
}
当发出事件时,我现在收到错误:
未捕获的ReferenceError:未定义myOwnFunction 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)
答案 0 :(得分:1)
使用arrow function
它会绑定context
。要拨打同一function
中存在的任何class
,我们需要使用this
关键字。像这样:
this.myOwnFunction() //it will call the 'myOwnFunction' function
使用arrow function
:
ipcRenderer.on('receiveData', () => { //use arrow function
this.myOwnFunction()
});
注意:以上代码可以使用,但请确保bind
方法为onButtonClick
。