I was just wondering why render() has 'this' set to a 'correct' or intuitive value by default, but then any other methods I define on a component must have 'this' explicitly set?
For example:
class App extends React.Component {
constructor (props) {
super(props);
}
onFormSubmit (e) {
e.preventDefault();
console.log(this);
}
render () {
console.log(this);
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input type="search"/>
<button>Submit</button>
</form>
</div>
);
}
}
ReactDOM.render(
<App/>,
document.getElementById('app')
);
The console output of the above is
App {props: Object, context: Object...}
null
Why is that? Is there any way to make it so that, by default, this
will refer to the App
in both cases? Or do I just need to keep writing this.onFormSubmit = this.onFormSubmit.bind(this);
in the constructor
?
Maybe it makes no sense to want this behaviour by default (I am very new to programming!) but if that is the case please do explain why :)
All the best
[edit] Also... why is it that this
returns null
when referenced inside the onFormSubmit function?