[英]Why value from a Material-UI Button is not being passed to the onClick event handler?
I am trying to pass a value from a Material-UI Button when it's clicked to it's click handler, but it's always showing value
of undefined
.我试图从 Material-UI 按钮单击它的单击处理程序时传递一个值,但它始终显示
undefined
的value
。 Earlier when I was using a simple button, I was getting value
but not after.早些时候,当我使用一个简单的按钮时,我获得了
value
,但之后却没有。
const categoryChangedHandler = (e) => {
console.log("category choosed ========= " + e.target.value);
setCategory(e.target.value);
};
<Button className="CategoryButton" variant="outlined" color="primary"
value={category}
onClick={e => categoryChangedHandler(e)}
style={{ textAlign: 'center' }}
>
{category}
</Button>
and I am getting the result:我得到了结果:
category choosed ========= undefined
You need to use event.currentTarget.value
instead of event.target.value
.您需要使用
event.currentTarget.value
而不是event.target.value
。
The text of a Material-UI Button
is within a <span>
inside a <button>
element. Material-UI
Button
的文本位于<button>
元素内的<span>
内。 When you click on the text, event.target
will refer to the span element;当你点击文本时,
event.target
将引用 span 元素; whereas event.currentTarget
will refer to the element with the event handler attached (ie the button element) that the click event bubbled up to.而
event.currentTarget
将引用附加了事件处理程序的元素(即按钮元素),单击事件冒泡到该元素。
Here's a simple working example:这是一个简单的工作示例:
import Button from "@material-ui/core/Button";
export default function App() {
return (
<Button value="hello" onClick={(e) => console.log(e.currentTarget.value)}>
Hello World
</Button>
);
}
Related answer:相关答案:
Documentation:文档:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.