React按钮传值实现:点击学生/教师按钮在handleSwitcher分别打印10和20
实现方案
推荐使用传参绑定的方案,逻辑直观没有兼容性问题,修改步骤如下:
- 修改
handleSwitcher函数,接收数值参数:
const handleSwitcher = async (printVal) => { console.log(printVal) }
- 调整两个按钮的点击事件绑定,点击时传入对应要打印的值,同时为了避免点击图片外的按钮区域不触发,建议把
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
相关产品推荐
相关产品推荐

