0
我不知道爲什麼我得到這個錯誤。我只是撥打this.sendTranslation
。我認爲它可能是e.preventDefault()
系列,但事實並非如此。有什麼不對?如何從Popup.checkIfEnterPressed
內撥打sendTranslation
?反應:未捕獲TypeError:無法讀取null的屬性'sendTranslation'
import React from "react";
import "../../styles/popup.css";
export default class Popup extends React.Component {
constructor(props) {
super(props);
// STATE
this.state = {
word: "",
translation: ""
};
// BINDINGS
this.handleChange = this.handleChange.bind(this);
this.sendTranslation = this.sendTranslation.bind(this);
}
sendTranslation() {
// send translation to background.js
chrome.runtime.sendMessage(
{ wordsPair: [this.state.word, this.state.translation] },
function(response) {
window.close();
}
);
}
checkIfEnterPressed(e) {
if (e.keyCode == 13) {
e.preventDefault(); // to prevent calling handleChange
this.sendTranslation();
}
}
handleChange(e) {
const name = e.target.name;
this.setState({
[name]: e.target.value
});
}
render() {
return (
<div id="container">
<header>Fishky</header>
<div className="word field">
<input
type="text"
name="word"
placeholder="Word"
value={this.state.word}
onKeyUp={this.checkIfEnterPressed}
onChange={this.handleChange}
/>
</div>
<div className="translation field">
<input
type="text"
name="translation"
placeholder="Translation/Definition"
value={this.state.translation}
onKeyUp={this.checkIfEnterPressed}
onChange={this.handleChange}
/>
</div>
<div className="submit-word">
<button
type="button"
className="btn btn-default btn-block"
id="submit-popup"
onClick={this.sendTranslation}
>
add
</button>
</div>
</div>
);
}
}
錯誤。爲什麼我會得到空?
Uncaught TypeError: Cannot read property 'sendTranslation' of null
at checkIfEnterPressed (Popup.js:31)
at Object.ReactErrorUtils.invokeGuardedCallback (ReactErrorUtils.js:69)
at executeDispatch (EventPluginUtils.js:85)
at Object.executeDispatchesInOrder (EventPluginUtils.js:108)
at executeDispatchesAndRelease (EventPluginHub.js:43)
at executeDispatchesAndReleaseTopLevel (EventPluginHub.js:54)
at Array.forEach (<anonymous>)
at forEachAccumulated (forEachAccumulated.js:24)
at Object.processEventQueue (EventPluginHub.js:254)
at runEventQueueInBatch (ReactEventEmitterMixin.js:17)