简体   繁体   中英

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 . Earlier when I was using a simple button, I was getting value but not after.

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 .

The text of a Material-UI Button is within a <span> inside a <button> element. When you click on the text, event.target will refer to the span element; whereas event.currentTarget will refer to the element with the event handler attached (ie the button element) that the click event bubbled up to.

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>
  );
}

编辑按钮 currentTarget

Related answer:

Documentation:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM