jun*_*unk 0 components reactjs
例如,我需要通过“this”获取组件对象,但“this”未定义
成分:
<Menu onClick ={()=>this.MenuNavigate()}/>
Run Code Online (Sandbox Code Playgroud)
原型函数:
React.Component.prototype.MenuNavigate = (e) => {
// let url = e.item.props["data-url"]
console.log(this)->undefined
}
Run Code Online (Sandbox Code Playgroud)
如何得到“这个”?
我认为所有组件都扩展了 React.Component,所以我想在所有扩展了 React.Component 的组件中使用函数,因为我不需要再次编写
this未定义,因为您使用了具有词法作用域的箭头函数this,即它绑定到定义它的上下文,而不是绑定到正在调用它的对象。
使用函数表达式可以解决这个问题:
React.Component.prototype.MenuNavigate = function(e){
console.log(this);
}
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/69z2wepo/70670/
但我不会走这条路。@Canastro 在另一个答案中建议的是一种很好的方法,另一种方法可能是高阶组件,它可以环绕您的组件并提供 MenuNavigat 功能。
| 归档时间: |
|
| 查看次数: |
13383 次 |
| 最近记录: |