首页 > 解决方案 > 如何将一个映射函数的迭代器作为参数传递给另一个函数

问题描述

我的文件中有 2 个地图功能。我希望在每次单击按钮时将第二个映射函数的迭代器变量作为另一个函数的参数传递。相当新的反应所以不知道我应该怎么做才能使它正确

return (    
<Table className={classes.table} aria-labelledby="tableTitle">
        <EnhancedTableHead />

        <TableBody>
          {dataList.map((item, item_idx) => {

return (
                <TableRow
                  hover
                  tabIndex={-1}
                  key={item.id}
                >
                  <TableCell padding="checkbox">
                  </TableCell>
                  <TableCell  padding="none">
                      {item.dataName}--{item.datatId}
                  </TableCell>
                  <TableCell padding="none"  ><SwitchButton/></TableCell>
                  <TableCell    >


{
  this.state.user.map((ab, ab_idx) =>
  <li className = "display">

{isSwitchOn === false ?  <input  type = 'search' placeholder = "id"  id="name" name = "name"  onChange={(e) => this.handleidChange(e,ab_idx)}/>: " All"}
{isSwitchOn === false ? <a href="javascript:void(0)" className = "removeIcon" style={{display:(this.state.user.length > 1 )? "inline" : "none"}} onClick={() => {this.removeItem(this.state,ab_idx)}}   >Remove</a> : "" }

</li>
     )}


</TableCell>
                  <TableCell  padding="none">
                   <Button className="user-edit-btn" style={{display:(isSwitchOn === false) ? "block" : "none", textTransform: 'capitalize',}}  variant="contained" onClick={() => {this.insertTextBox(item)}}  >
                  Add User
                  </Button>
                </TableCell>
                </TableRow>
              );

            })}

          {(
            <TableRow style={{ height: 49 }}>
              <TableCell colSpan={6} />
            </TableRow>
          )}
        </TableBody>
      </Table>
)

每当我单击添加用户按钮时,我希望将“ab”作为函数 insertTextBox(item) 的参数传递。虽然这样做给了我一个错误“错误:相邻的 JSX 元素必须被包裹在一个封闭的标签中。你想要片段吗??”

标签: javascriptreactjsmap-function

解决方案


您需要handleidChange像这样在构造函数中绑定:

this.handleidChange = this.handleidChange.bind(this)

那么你的处理程序应该是这样的:

handleidChange(ab_idx, e){
   //do smth
}

然后以这种方式传递处理程序:

<input  type = 'search' placeholder = "id"  id="name" name = "name"  
onChange={this.handleidChange.bind(this, ab_idx)}/>`

推荐阅读