ES6类继承问题

export default class Base extends Component<Props> {
    constructor(props) {
        super(props);
        console.log("Base this",this)//打印this 可以看到箭头函数showToast 但是不能看到renderModal
    }

    /*
    *显示Toast
    * */
    showToast=(msg)=>{
        console.log("showToast",this)
    }

    /**
     *显示弹出框
     * */
    renderModal(contentView, visible, close, animation, customerlayout){
     console.log("renderModal",this)
    }


    componentDidMount() {
    }

    componentWillUnmount() {
    }

}

在子类中使用时

super.renderModal("hahahhah")//正确
 super.showToast("hahahhah")//报错如下

clipboard.png

打印base的this可以看到箭头函数的名字
clipboard.png

求详细解释

阅读 2.5k
2 个回答

这个和箭头函数没有关系。

其实只有第二种写法是 es6 的 class 语法:

class Base {
    constructor() {
        console.log("constructor")
    }

    fn(){
     console.log("fn")
    }

}

而 class 本质上还是 js 的原型链继承,因此这个函数其实是在 class 实例的原型链上:

而 showToast=(msg)=>{} 语法,虽然 React-Native 可以使用,但是这个需要靠 babel 编译。这个是 Stage 3 的提案 class-fields,也就是曾经被废弃的 Stage2 的 class-public-fields

你可以把字类的 2 个 super 改成 this

this.renderModal("hahahhah")//正确
this.showToast("hahahhah")//报错如下

箭头函数没有自己的this。它的this并不是像你想的那样指向当前子类或base对象,而是在定义的时候的当前对象。如果你是在全局作用域下创建的base类,那就是undefined。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题