React部分
Cannot read property ‘setState’ of null
具体错误
Uncaught TypeError: Cannot read property ‘setState’ of null
问题描述
使用ES6class 语法糖创建组件时, 在render 之前添加类内函数,如下:
onReset() {
......
}
这本身没有毛病,但如果要使用this.setState() 时,控制台报错:Cannot read property ‘setState’ of null,打印此处的this ,得到的是null。
解决方案
将之前的类内函数声明改为函数表达式(ES6的方式),如下:
onReset = () => {
......
}
参考链接
- javascript - Uncaught TypeError: Cannot read property ‘setState’ of …
- Autobinding, React and ES6 Classes
- official React blog#autobinding
Less部分
calc()函数计算结果不正确
描述
在less文件中使用CSS原生的calc()函数,得出的结果错误,在less中 calc(100% - 4rem) 等带单位混合运算会被less解析忽略单位,全部按照百分比计算,此例中的计算被less编译成calc(96%)。
原因分析
less的计算方式跟calc方法有重叠,两者在一起有冲突
解决方案
更改calc()函数的形式
/*编译错误的css:calc(100% - 4rem)*/
/*更改形式如下,以下两种方法皆可*/
width:e("calc(100% - 4rem)");
width:calc(~"100% - 4rem");

本文解决React组件中使用class语法糖时遇到的“Cannot read property ‘setState’ of null”错误,并提供正确的函数绑定方法。同时,针对LESS中calc函数计算结果不准确的问题给出了解决方案。
3293

被折叠的 条评论
为什么被折叠?



