Home > OS >  The getAttribute function is not always retrieving the attribute value
The getAttribute function is not always retrieving the attribute value

Time:11-21

enter image description here

CodePudding user response:

The <svg> element will only be the target if it's the innermost item clicked on. If you click on the <path> part of the SVG, for example, that'll be the target instead.

While you could fix it by using event.currentTarget instead - which will reference the element the listener was attached to instead of the element the event was dispatched to - since this is React, a much better approach would be not to pass information through the DOM at all, and to instead convey it through JavaScript alone.

For example, you could have something like:

  makeHandler(name) {
    return () => {
      console.log(name);
    };
  }
  render() {
    return (
      <div>
        <div style={{ height: "30px", width: "30px" }}>
          <FirstSVG onClick={makeHandler("first_page")} />
        </div>
        <div style={{ height: "30px", width: "30px" }}>
          <BackSVG onClick={makeHandler("back_page")} />
        </div>
      </div>
    );
  }

CodePudding user response:

The target property refers to the dom element on which the event originated so you have to use currentTarget just like this:

handleSearchChange(event) {
    const target = event.currentTarget;
    const name = target.getAttribute("name");
    console.log("Test name "   name   "\n");
}

if you would like to know more about difference between target and currentTarget see this here or here

  • Related