Home > Mobile >  When I click the image button, the console displays undefined
When I click the image button, the console displays undefined

Time:11-17

import React, { Component } from "react";
import Person from "./Person.js";

class App extends Component {
  clickHandler = (event) => {
    event.preventDefault();
    const data = event.target.value;
    console.log(data);
  };
  url =
    "https://th.bing.com/th/id/OIP.eBSw-Azi3SfBlttoGOip1gHaEr?w=297&h=187&c=7&r=0&o=5&dpr=1.3&pid=1.7";
  render() {
    return (
      <div className="App">
        <div onClick={this.clickHandler}>Test1</div>
        <Person clickHandler={this.clickHandler}>Test2</Person>
        <button type="button" value="Dog" onClick={this.clickHandler}>
          <img src={this.url} alt="Funny Dog" />
        </button>
      </div>
    );
  }
}

export default App;

As you can see, I have defined the value of the button, and when I click on it, the console should display "Dog". Why is it showing "Undefined"? 

CodePudding user response:

const data = event.currentTarget.value;

Use currentTarget instead of target. The difference between target and eventTarget is that eventTarget gives the element on which event listener is attached while target gives the element on which user has clicked.

  • Related