I face a question as flow:
class App extends React.Component {
testop(){
alert("test");
}
showAlert() {
// alert("Im an alert");
this.testop();
}
render() {
return <button onClick={this.showAlert}>show alert</button>;
}
}
when I run the code, the error is "Uncaught TypeError: Cannot read properties of undefined (reading 'testop')". why cannot read testop function?
CodePudding user response:
The problem is that the this you are referring to inside showAlert is not referring to component's this instead it is referring to the internal methods this.
There are two solutions for this problem.
Either bind the function with component's this inside the component's constructor:
constructor (){
this.showAlert = this.showAlert.bind(this);
}
Or use ES6's arrow function which provides lexical scoping
CodePudding user response:
or try to use arrow function instead of binding
showAlert = () => {
this.testop();
}
https://codesandbox.io/s/tender-ully-1ynyqm?file=/src/App.js
