Thanks guys, this turned out to be my own confusion about the grammar of ES6 class.
But I asked this question because I encountered the following problem.
I was learning React and I have the following snippet of code.
import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props){
super(props);
}
render() {
// console.log(this);
return <div>
<input
onChange={ this.onInputChange }
/>
</div>;
}
onInputChange(event) {
console.log(this);
}
}
export default SearchBar;
Fairly simple, this code will generate an input component and when things within it changes, we log out 'this'.
However, this code will generate 'undefined' all the time.
As I know that 'this' within the object child function should point to object itself, why this is happening?
By the way, the main js file looks like this.
import ReactDOM from 'react-dom';
import React from 'react';
import SearchBar from './components/search_bar';
const API_KEY = 'AIzaSyCdAXs0YXxqGUKjb4sZsmsF_hHq_f3PJmY';
const App = () => {
return (
<div>
<SearchBar />
</div>
);
}
ReactDOM.render(<App />, document.querySelector('.container'));
And the html looks like this
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/style/style.css">
<link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">
<script src="https://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
<div class="container"></div>
</body>
<script src="/bundle.js"></script>
</html>
where bundle.js is the output react script with bable.