才學(xué)react幾天求問大神react的this問題classAppextendsReact.Component{//constructor(props){//super(props)//}state={name:'ls'}render(){return點擊觸發(fā)事件}fn(){console.log(1);console.log(this);}}為什么點擊之后這里的this是打印的undefined而不是這個實例我知道4個解決辦法但是我就是搞不懂為什么this指向的undefined按理說這里this.fn觸發(fā)了不就是對象里面方法的調(diào)用嗎既然這樣方法里面的this不就是指向這個對象的嗎為什么會是undefined聽大佬說這個this指的是點擊這個事件所以是undefined那我用箭頭函數(shù)為什么就又可以了(箭頭函數(shù)沒有this,this會不斷往上作用域鏈尋找)classAppextendsReact.Component{//constructor(props){//super(props)//}state={name:'ls'}render(){return點擊觸發(fā)事件}fn=()=>{console.log(1);console.log(this);}}
react里面的this指向問題
人到中年有點甜
2019-10-16 11:17:09