React学习笔记-2

关于this的指向问题

  • 函数内的this取决于函数在什么地方被调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
export default class TodoList extends Component {
constructor(props) {
super(props)
this.state = {
list: [],
text:''
}
// 官方建议 在这里 bind(this) onChange事件里就不用显式声明e
this.handleChange = this.handleChange.bind(this)
// 即使不使用 e 但只要是在onClick事件中调用的函数,都要绑定this
}
handleChange(e) {
console.log(e.target.value);
this.setState({
text: e.target.value
}, () => {
// 回调函数,在这里拿到正确的修改后的值
console.log(this.state.text);
})
}
...
}