You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React使用map动态渲染时onClick事件传参错误问题求助

问题原因

你代码的语法错误出在Button的onClick事件传参部分:

  • 在JS的函数参数里不需要加JSX插值用的{}符号,你写的{i+1}和{email}会被解析为对象字面量,而对象字面量中不能直接写i+1这种表达式作为未命名的键,所以触发了语法报错。
  • 你需要根据addquantity的定义方式,调整传参写法:如果函数接收两个独立参数,直接去掉多余的大括号即可;如果函数接收单个对象参数,需要补充对应的键名。

修正方案

方案1:传递两个独立参数(适配addquantity接收两个参数的场景)

把onClick对应行改为:

<Button onClick={() => addquantity(i+1, email)}>Button</Button>

方案2:传递单个对象参数(适配addquantity接收对象参数的场景)

补充键名后写法为:

<Button onClick={() => addquantity({ index: i+1, email })}>Button</Button>

完整修正代码示例(以方案1为例)

<Container>
  <Row xs={3} md={4} lg={6}>
    {[...Array(numberOfCards)].map((e, i) => {
        return (
          <Col className='mt-5' key={i+1}> 
              <Card >
                  {/* <Card.Img top width="100%" src="/images/companylogo.png" alt="Card image cap"/> */}
                  <Card.Body>
                      <Card.Title tag="h5">Card title</Card.Title>
                      <Card.Subtitle tag="h6" className="mb-2 text-muted">Card subtitle</Card.Subtitle>
                      <Card.Text>Some quick example text to build on the card title and make up the bulk of the
                          card's
                          content.</Card.Text>
                      <Button onClick={() => addquantity(i+1, email)}>Button</Button>
                  </Card.Body>
              </Card>
          </Col>
        )
    })}
  </Row>
</Container>

内容的提问来源于stack exchange,提问作者NooB Gamer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 12:24:07