I was working on my React project with Material-ui, and noticed a strange (?) way for writing an event handler:
https://codesandbox.io/s/8091z?file=/demo.js
In above example, the handler for checkbox is defined as:
const handleToggle = (value) => () => {
const currentIndex = checked.indexOf(value);
const newChecked = [...checked];
if (currentIndex === -1) {
newChecked.push(value);
} else {
newChecked.splice(currentIndex, 1);
}
setChecked(newChecked);
};
What I usually do is just:
const handleToggle = (value) => {
const currentIndex = checked.indexOf(value);
const newChecked = [...checked];
if (currentIndex === -1) {
newChecked.push(value);
} else {
newChecked.splice(currentIndex, 1);
}
setChecked(newChecked);
};
The result is the same. So what is the specific reason to write handlers this way?
Just for shorter code when using the function?
Thank guys! And sorry for not being clear...
I understand the difference of using these 2 handlers.
For the first one, I use it like onClick={handleToggle(value)}
;
and for the second one, onClick={() => { handleToggle(value) }}
.
Just wondering which one is preferred.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…