React中constructor(){}
来源:互联网 发布:好伙伴物流软件 编辑:程序博客网 时间:2024/05/27 16:43
当你在React class中需要设置state的初始值或者绑定事件时
需要加上constructor(){}
但当你运行时,是会出现问题的。
提示没有在this之前加上super()
其实就是少了super(),导致了this的 Reference Error
个人理解super()是继承了整个类的一个引用(希望知道的帮忙解释下)
正确的姿势应该是这样
那么React的官方例子中都是加上了props作为参数
那它们的区别在哪儿呢
What's the difference between “super()” and “super(props)” in React when using es6 classes?
借用下stackoverflow上的解释
There is only one reason when one needs to pass props
to super()
:
When you want to access this.props
in constructor.
(Which is probably redundant since you already have a reference to it.)
只有一个理由需要传递props作为super()的参数,那就是你需要在构造函数内使用this.props
那官方提供学习的例子中都是写成super(props),所以说写成super(props)是完全没问题的,也建议就直接这样写
阅读全文
0 0
- React中constructor(){}
- React中constructor(){}究竟是什么
- Javascript中Constructor解剖
- Javascript中constructor作用
- C++中copy constructor
- 关于c++中 copy constructor
- GCC中 __attribute__((constructor)|(destructor))
- js中typeof和constructor
- Constructor
- Constructor
- constructor
- constructor
- constructor
- constructor
- constructor
- Javascript中this、prototype、constructor的理解
- java中构造器(Constructor)
- boa constructor中没有控件的问题
- [USACO17OPEN]Where's Bessie? 贝西在哪呢
- CatBoost: A machine learning library to handle categorical (CAT) data automatically MACHINE LEARNING
- 这是别人的添加监听事件的方法
- bootstrap之transition
- Badboy自动化测试工具6 Variable Setter
- React中constructor(){}
- 闵神的数论
- 类的概述·main方法中参数String[] argv的意义讲解
- 主成分分析(PCA)
- python基础系列教程——python中的字符串和正则表达式全解
- CentOS 7安装Python3.5
- Qt:自定义进度条
- 找新朋友(欧拉定理)
- 不想提交表单但是想利用表单校验功能