[英]React Beginner Question: Confusing Arrow Function Example
I'm a React/ES6 beginner and I'm using this code I found to handle a checkbox inside a custom component being clicked (the custom component includes a material-ui CheckBox, hence the "checked" value). 我是一名React / ES6初学者,我正在使用此代码来处理正在单击的自定义组件中的复选框(该自定义组件包括material-ui CheckBox,因此为“ checked”值)。 I'm planning on adding more fields to the custom component, such as a textbox that corresponds to the checkbox where the user can add more information about the box they checked.
我计划在自定义组件中添加更多字段,例如与复选框相对应的文本框,用户可以在其中添加有关其选中框的更多信息。
Anyway, I'm a bit confused about what's going on in that first line. 无论如何,我对第一行发生的事情感到有些困惑。 I was hoping one of you senior level devs could break it down for me so i can understand what's happening here.
我希望你们中的一位高级开发人员可以帮我分解一下,以便我能理解这里发生的事情。
Two things to note: 有两件事要注意:
checked is false by default but console logs as true (is it being toggled true somehow?) 默认情况下,checked为false,但控制台日志为true(是否以某种方式将其切换为true?)
const onMediaDeliverableChange = index => ({ target: {checked} }) => { console.log('>> [form.js] (onMediaDeliverablesChange) index = ',index); console.log('>> [form.js] (onMediaDeliverablesChange) target = ',checked); }
Here's an example of code that I took this from, that is working. 这是我从中获取代码的示例,该示例正在起作用。
const onCheckBoxChange = index => ({ target: { checked } }) => {
const newValues = [...values];
const value = values[index];
newValues[index] = { ...value, checked };
console.log('>> [form.js] (onCheckBoxChange) value = ',value, index);
console.log('>> [form.js] (onCheckBoxChange) newValues[index] = ',newValues[index]);
props.setDesignOrDigital(newValues);
};
The following: 下列:
const onCheckBoxChange = index => ({ target: { checked } }) => {
// stuff
};
could also be written as: 也可以写成:
const onCheckBoxChange = index => (event) => {
const checked = event.target.checked;
// stuff
};
{ target: { checked } }
is an example of using object destructuring on a function argument. { target: { checked } }
是在函数参数上使用对象分解的示例。 In this case, the argument would be an event. 在这种情况下,参数将是一个事件。
The first part: 第一部分:
index => another-function
is, as svey mentioned in the comments, an example of a curried function. 正如评论中提到的svey一样,它是咖喱函数的一个示例。 I assume onCheckBoxChange was used in a loop where the index of the checkbox being rendered was passed in which then returns a function that is an event handler for the change event.
我假设在循环中使用了onCheckBoxChange,在该循环中传递了要呈现的复选框的索引,然后在循环中返回了一个函数,该函数是change事件的事件处理程序。 The
index
is then used to get/set the checked state for the respective checkboxes. 然后使用
index
获取/设置各个复选框的选中状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.