React笔记-一些要注意的点

前端之家收集整理的这篇文章主要介绍了React笔记-一些要注意的点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


在React中要注意在componentWillUpadate 中不能用 this.setState() 方法

componentWillUpadate

问题的出现

在学习的时候,有一个例子的要求是,

使用componentWillUpdate()方法修改示例代码,使时钟在秒为0时显示为红色字体!

我一开始在componentWillUpadate()中 写的是

……
 componentWillUpadate:function(){
   if(this.state.time.split(':')[2] === '00'){
        this.state. = 'red';
    }
 }
……

程序报bug了。

我去找原因:

You cannot use this.setState() in componentWillUpadate . If you need to update state in response to a prop change,use componentWillReceiveProps instead.

代码如下:

官网上上说的是在componentWillUpadate 中不能用 this.setState() 方法

设置组件style

设置组件中的style属性时,要双大括号:

<div className="ez-digi-clock"  style={{color:this.state.color}}>
    {this.state.time}
</div>

这是因为 React 组件样式是一个对象,所以第一重大括号表示这是 JavaScript 语法,第二重大括号表示样式对象

原文链接:https://www.f2er.com/react/304224.html

猜你在找的React相关文章