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;
可以看到,我已经定义了按钮的值,当我单击它时,控制台应该显示"Dog"。为什么显示"未定义"?
const data = event.currentTarget.value;
使用currentttarget代替target。target和eventTarget之间的区别在于eventTarget给出了事件侦听器所附加的元素,而target给出了用户所单击的元素。