forked from vasanthk/react-bits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
22.event-handlers.jsx
74 lines (64 loc) · 2.29 KB
/
22.event-handlers.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Binding event handlers in the constructor.
*/
// Most of the times we handle DOM events in the component that contains the elements dispatching the events.
// Like in the example below, we have a click handler and we want to run a function or method of the same component:
class Switcher extends React.Component {
render() {
return (
<button onClick={ this._handleButtonClick }>
click me
</button>
);
}
_handleButtonClick() {
console.log('Button is clicked');
}
}
// That's all fine because _handleButtonClick is a function and we indeed pass a function to the onClick attribute.
// The problem is that as it is the code doesn't keep the scope. So, if we have to use this inside _handleButtonClick we'll get an error.
class Switcher extends React.Component {
constructor(props) {
super(props);
this.state = { name: 'React in patterns' };
}
render() {
return (
<button onClick={ this._handleButtonClick }>
click me
</button>
);
}
_handleButtonClick() {
console.log(`Button is clicked inside ${ this.state.name }`);
// leads to
// Uncaught TypeError: Cannot read property 'state' of null
}
}
// What we normally do is to use bind like so:
<button onClick={ this._handleButtonClick.bind(this) }>
click me
</button>
// However, this means that the bind function is called again and again because we may render the button many times.
// A better approach would be to create the bindings in the constructor of the component:
class Switcher extends React.Component {
constructor(props) {
super(props);
this.state = { name: 'React in patterns' };
this._buttonClick = this._handleButtonClick.bind(this);
}
render() {
return (
<button onClick={ this._buttonClick }>
click me
</button>
);
}
_handleButtonClick() {
console.log(`Button is clicked inside ${ this.state.name }`);
}
}
// The other alternative is to use arrow functions for the onClick prop function assignment,
// Arrow functions auto binds the function with `this`
// Facebook by the way recommend the same technique while dealing with functions that need the context of the same component.
// The binding in the constructor may be also useful if we pass callbacks down the tree.