才学react几天 求问大神react的this问题
class App extends React.Component {
// constructor(props){
// super(props)
// }
state={
name:'ls'
}
render() {
return <button onClick={ this.fn }>点击触发事件</button>
}
fn() {
console.log(1);
console.log(this);
}
}
为什么点击之后这里的this是打印的undefined 而不是这个实例
我知道4个解决办法 但是我就是搞不懂为什么this指向的undefined
按理说这里this.fn触发了 不就是对象里面方法的调用吗 既然这样 方法里面的this不就是指向这个对象的吗
为什么会是undefined
听大佬说 这个this指的是点击这个事件 所以是undefined
那我用箭头函数为什么就又可以了(箭头函数没有this,this会不断往上作用域链寻找)
class App extends React.Component {
// constructor(props){
// super(props)
// }
state={
name:'ls'
}
render() {
return <button onClick={ this.fn }>点击触发事件</button>
}
fn = ()=>{
console.log(1);
console.log(this);
}
}
你要在constructor里把fn里的this指向绑定到这个组件。
还有state写到constructor函数里