Reputation: 495
One thing that confuses me is the onChange event. As the code below, onChange event work with handleChange function. So what confuses me here is the event parameter.
class ControlledInput extends React.Component {
constructor(props) {
super(props);
this.state = {
input: "empty"
};
// change code below this line
this.handleChange = this.handleChange.bind(this);
// change code above this line
}
// change code below this line
handleChange(event) {
this.setState({
input: event.target.value
})
}
// change code above this line
render() {
return (
<div>
{ /* change code below this line */}
<input type="text" value={this.state.input} onChange={this.handleChange}></input>
{ /* change code above this line */}
<h4>Controlled Input:</h4>
<p>{this.state.input}</p>
</div>
);
}
};
Does every function work with onChange event need to have a parameter. If the answer is yes, why?
I replaced the keyword ‘event’ with some other keywords and it still works normally. So is it okay if I use a different word instead of the keyword ‘event’?
Upvotes: 2
Views: 253
Reputation: 13071
Does every function work with onChange event need to have a parameter. If the answer is yes, why?
They don't need to use the event parameter, therefore you don't need to declare that parameter in the callback function and the function will get called anyways (the invoker will still pass the parameter, of course, but you can ignore it if you don't need it). However, if you want to know what has changed, then you probably will want to use the info of the event parameter, right?
I replaced the keyword ‘event’ with some other keywords and it still works normally. So is it okay if I use a different word instead of the keyword ‘event’?
The word event
is not a reserved word in JavaScript, you can name the parameter of the function however you want, it will still work just the same, yes.
Maybe the following example will help you understand how callbacks work with JS.
Consider the following function... What it does is it lets you register a function that will get invoked every certain number of milliseconds. Whenever the function gets invoked you will receive the current epoch time:
const timerSubscription = (ms, fn) => {
const id = setInterval(() => {
fn(Date.now());
}, ms);
return () => clearInterval(id);
}
So you could use it like this:
let count = 0;
const unsubscribe = timerSubscription(1000, () => {
count++;
console.log('One second passed');
if (count === 5) {
unsubscribe();
}
});
Or you could use it like this:
let start = Date.now();
const unsubscribe = timerSubscription(1000, (now) => {
console.log('One second passed');
if (now + 5000 >= start) {
unsubscribe();
}
});
They do almost exactly the same thing, one uses the argument that the invoker passes to it and the other one doesn't. Either way the invoker is always passing the argument.
Upvotes: 2