点击Material-UI图标时按钮删除功能失效且name为undefined如何解决
问题原因
点击事件的target属性指向的是实际触发事件的最内层DOM元素:
- 点击按钮空白区域时,
e.target就是你绑定了name属性的<button>元素,能正常拿到属性值 - 点击图标时,
e.target是Material-UI图标渲染出来的<svg>/<span>元素,该元素没有设置name属性,所以取值为undefined,导致请求参数错误。
修复方案
按推荐优先级排序如下:
方案1(最便捷,推荐):使用e.currentTarget替代e.target
currentTarget属性永远指向绑定了点击事件监听器的元素,也就是你的<button>,无论点击内部哪个子元素都能正确拿到属性。
修改deletePost函数里的取值代码即可:
function deletePost(e){ e.preventDefault(); if(window.confirm("Are you sure to delete")) { // 把e.target换成e.currentTarget let {name} = e.currentTarget; console.log(name); $.post("http://localhost:4000/delete" , {name}) .done(res=>{ setAll({value:res}); console.log(allPosts); }) .fail(e=>{console.log(e);}) } }
方案2:禁止图标响应点击事件
给图标添加pointer-events: none样式,让它不接收鼠标事件,点击图标会直接穿透到下层的按钮元素:
<button name={props.id} onClick={deletePost}> <DeleteOutlineOutlinedIcon style={{pointerEvents: 'none'}} /> </button>
方案3:直接传递ID参数(避免依赖事件对象)
绑定点击事件的时候直接把ID作为参数传入处理函数,不用从事件对象读取属性,逻辑更直观:
按钮代码修改为:
<button onClick={(e) => { e.preventDefault(); deletePost(props.id); }}> <DeleteOutlineOutlinedIcon /> </button>
deletePost函数修改为:
function deletePost(postId){ if(window.confirm("Are you sure to delete")) { console.log(postId); $.post("http://localhost:4000/delete" , {name: postId}) .done(res=>{ setAll({value:res}); console.log(allPosts); }) .fail(e=>{console.log(e);}) } }
内容的提问来源于stack exchange,提问作者chaos
相关产品推荐
相关产品推荐

