我正在尝试使用map函数生成组件,但是具有索引的onChange函数为我增加了值 为什么这给我错误的索引?
当前数组有两个对象
await t
.typeText()
.click()
.expect()
.eql()
.then()
//这是我的句柄函数。
{projectState.labels.map((i, k) => (
<>
{k === 0 && (
<>
<Grid container item xs={12}>
<Grid item xs={10}>
<Autocomplete
id="main"
ref={(ref) => (autoCompleteRef.current[k] = ref)}
name={`label${k + 1}`}
options={labelData}
getOptionSelected={(option, value) =>
option.title === value.title
}
getOptionLabel={(option) =>
option.title ? option.title : ""
}
classes={{ paper: classes.paper }}
ListboxProps={{ style: { maxHeight: "180px" } }}
// inputValue={labelData[labelData.length - 1].title}
onChange={handleMainLabelFromDropdown(k)}
renderInput={(props) => (
<TextFieldWithInFocusHelp
{...props}
required
label={`Main Label ${k + 1}`}
help="Select the label for the non-defective classification. No sub-labels are allowed for this category."
/>
)}
/>
</Grid>
<Grid container item xs={1} alignItems="center">
<TooltipStyled
placement="right"
title="Add new main label."
>
<IconButton onClick={toggleNewLabelDialogOpen}>
<AddCircleIcon color="primary" fontSize="large" />
</IconButton>
</TooltipStyled>
<NewLabelDialog
open={newLabelDialogOpen}
onClose={toggleNewLabelDialogOpen}
onChange={hanldeMainLabelFromDialog(k)} <--- this is child component. this index returns 1
/>
</Grid>
</Grid>
</>
)}
答案 0 :(得分:1)
将您的onChange更改为此:onChange={() => hanldeMainLabelFromDialog(k)}
,您正在招惹您的处理程序。更改为
const hanldeMainLabelFromDialog = index => { }
如果您想从子元素返回值并传递索引,请将代码更改为
onChange={valueFromChild => hanldeMainLabelFromDialog(valueFromChild, k)}
和
const hanldeMainLabelFromDialog = (value, index) => { }