It depends on how you call the function and whether or not you bind it.
class Test extends React.Component {
clickHandler = function() {
console.log(this);
}
render() {
return (
<div>
<button onClick={this.clickHandler}>Option A</button>
<button onClick={this.clickHandler.bind(this)}>Option B</button>
<button onClick={() => this.clickHandler()}>Option C</button>
</div>
);
}
}
With the Option A button, the click handler is passed directly to the <button /> element. Since React assumes you bind this and won't do it for you, the this inside clickHandler will be undefined.
With the Option B button we're explicitly binding this.clickHandler to this, in which case the this inside clickHandler will refer to that specific instance of the Test component.
For Option C (which is what you're doing in your question) we are not setting this.clickHandler as the onClick handler, but we're defining a new arrow function that calls this.clickHandler. In this case, the new arrow function will automatically get the Test component as this and that one is passed along to clickHandler.
Note that the Option A version will allow components to explicitly bind the handler:
class Button extends React.Component {
render() {
return (
<button
onClick={this.props.onClick.bind(this)}
children={this.props.children}
/>
);
}
}
class Test extends React.Component {
clickHandler = function() {
console.log(this);
}
render() {
return <Button onClick={this.clickHandler}>Click</Button>;
}
}
In this case, this within Test.clickHandler() will actually be a reference to the Button instance.