React循环组件带有映射函数,索引错误



我试图用map函数生成组件,但具有索引的onChange函数给了我递增的值为什么这给了我错误的索引?

目前阵列有两个对象

{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>
</>
)}

//这是我的手柄功能。

const hanldeMainLabelFromDialog = index => value =>{
console.log(index)                   //It gives me 1. I thought it had to give me 0.
}

将onChange更改为:onChange={() => hanldeMainLabelFromDialog(k)}

你在讨好你的经纪人。更改为,

const hanldeMainLabelFromDialog = index => { }

编辑以回应评论

如果您想从子返回一个值并传递索引,请将代码更改为

onChange={valueFromChild => hanldeMainLabelFromDialog(valueFromChild, k)}

const hanldeMainLabelFromDialog = (value, index) => { }

相关内容

  • 没有找到相关文章

最新更新