You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/docs/handling-events.md
+7-7Lines changed: 7 additions & 7 deletions
Original file line number
Diff line number
Diff line change
@@ -58,40 +58,40 @@ In questo esempio, il parametro `e` è un evento sintetico (_synthetic event_).
58
58
59
59
Usando React, in generale, non dovresti aver bisogno di chiamare `addEventListener` per aggiungere listeners ad un elemento DOM dopo la sua creazione. Invece, basta fornire un listener quando l'elemento è inizialmente renderizzato.
60
60
61
-
Quando definisci un componente usando una [classe ES6](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Classes), un pattern comune è usare un metodo della classe come gestore di eventi. Ad esempio, questo componente `Toggle` renderizza un pulsante che consente all'utente di alternare gli stati "ON" e "OFF":
61
+
Quando definisci un componente usando una [classe ES6](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Classes), un pattern comune è usare un metodo della classe come gestore di eventi. Ad esempio, questo componente `Interruttore` renderizza un pulsante che consente all'utente di alternare gli stati "Acceso" e "Spento":
62
62
63
63
```js{6,7,10-14,18}
64
-
class Toggle extends React.Component {
64
+
class Interruttore extends React.Component {
65
65
constructor(props) {
66
66
super(props);
67
-
this.state = {isToggleOn: true};
67
+
this.state = {acceso: true};
68
68
69
69
// Necessario per accedere al corretto valore di `this` all'interno della callback
70
70
this.handleClick = this.handleClick.bind(this);
71
71
}
72
72
73
73
handleClick() {
74
74
this.setState(state => ({
75
-
isToggleOn: !state.isToggleOn
75
+
acceso: !state.acceso
76
76
}));
77
77
}
78
78
79
79
render() {
80
80
return (
81
81
<button onClick={this.handleClick}>
82
-
{this.state.isToggleOn ? 'ON' : 'OFF'}
82
+
{this.state.acceso ? 'Acceso' : 'Spento'}
83
83
</button>
84
84
);
85
85
}
86
86
}
87
87
88
88
ReactDOM.render(
89
-
<Toggle />,
89
+
<Interruttore />,
90
90
document.getElementById('root')
91
91
);
92
92
```
93
93
94
-
[**Provalo su CodePen**](https://codepen.io/gaearon/pen/xEmzGg?editors=0010)
94
+
**[Prova su CodeSandbox](codesandbox://handling-events/1.js)**
95
95
96
96
Fai attenzione al valore di `this` nelle callback JSX. In JavaScript, i metodi delle classi non sono [associati](https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_objects/Function/bind) (_bound_) di default. Se dimentichi di applicare `bind` a `this.handleClick` e di passarlo a `onClick`, `this` sarà `undefined` quando la funzione verrà effettivamente chiamata.
0 commit comments