There's something i've discovered recently but i'm not sure why it does work. I used to do this when making react components:
class App extends React.Component {
state = {
input: ''
}
onChangeHandler = event => {
this.setState({input: event.target.value});
}
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<input value={this.state.input} onChange={(event) => this.onChangeHandler(event)} />
</div>
);
}
}
I understand this is creating a new function each time it re-renders. So I remember reading somewhere that this also worked:
class App extends React.Component {
state = {
input: ''
}
onChangeHandler = event => {
this.setState({ input: event.target.value });
}
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<input value={this.state.input} onChange={this.onChangeHandler} />
</div>
);
}
}
I'm using the latter now since it doesn't create a new function for each re-render. The thing is, how does that work? How is the event getting to the handler if i'm not passing it as a parameter in the onChange prop in the input tag? I'm just passing the reference.
Sorry if this has been asked, I've had no luck searching for an answer.
Thanks!