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

React按钮传值实现:点击学生/教师按钮在handleSwitcher分别打印10和20

实现方案

推荐使用传参绑定的方案,逻辑直观没有兼容性问题,修改步骤如下:

  1. 修改handleSwitcher函数,接收数值参数:
const handleSwitcher = async (printVal) => {
  console.log(printVal)
}
  1. 调整两个按钮的点击事件绑定,点击时传入对应要打印的值,同时为了避免点击图片外的按钮区域不触发,建议把onClick绑定到Button组件而非内部的CImg上:
<Grid xs={4} style={{marginBottom: 20}}>
    <Button style={{display: 'inline-block'}} onClick={() => handleSwitcher(10)}>
      <CImg
      height={50}
      style={{margin: 10,}}
      />
      <div className={classes.constantia}>Student</div>
    </Button>
  </Grid>
  <Grid xs={4} style={{marginBottom: 20}}>
    <Button style={{display: 'inline-block'}} onClick={() => handleSwitcher(20)}>
      <CImg
      height={50}
      style={{margin: 10,}}
      />
      <div className={classes.constantia}>Teacher</div>
    </Button>
  </Grid>

如果你希望保留CImg上的value属性写法,也可以通过事件对象获取属性值:

const handleSwitcher = async (e) => {
  // 如果CImg透传了value属性,直接取e.target.value
  console.log(e.target.value)
  // 如果是自定义属性没有透传,把CImg的value改为data-value="10",用下方写法取值
  // console.log(e.target.dataset.value)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 02:45:00