React 中事件的使用
事件定义
1. 匿名函数的方式定义事件
2. 类函数的方式定义 this 指向会有问题
如何修正
a. render 函数通过 bind 进行修正 this.handleClick.bind(this)
<button onClick={this.handleClick.bind(this)}>添加todos</button>
b. 在构造函数中进行修正
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);}
c. 通过匿名函数的方式进行修正,如1,
handleClick = ()=>{}
handleClick = () => {
console.log(this);
let newTodos = JSON.parse(JSON.stringify(this.state.todos));
console.log(this.ref.current.value);
let todo = {
id: Date.now(),
text: this.ref.current.value,
};
newTodos.push(todo);
// 设置状态
this.setState({
todos: newTodos,
});
};
c. 在定义处使用箭头函数
<button onClick={() => {this.handleClick();}}> </button>