ReactJs学习笔记

来源:互联网 发布:西部世界知乎 编辑:程序博客网 时间:2024/05/20 13:07

刚开始接触的时候,一直看不懂代码,其实坚持一下,看多点就懂了。

react是先声明component,再把声明好的component加载到DOM,因为js加载DOM的速度比html加载要快很多,所有react很适用于前端对性能要求比较高的项目。

看了阮一峰老师的博客,做了一些笔记:

组件类的第一个字母必须大写,不然会报错


组件类只能包含一个顶层标签,以下代码有两个顶层标签,会报错

var HelloMessage = React.createClass({

  render:function(){

    return<h1>

      Hello {this.props.name}

    </h1><p>

      some text

    </p>;

  }

});



添加组件属性,有一个地方需要注意,就是 class 属性需要写成className for属性需要写成 htmlFor,这是因为 class for JavaScript 的保留字。


this.props.children 的值有三种可能:如果当前组件没有子节点,它就是 undefined ;如果有一个子节点,数据类型是object ;如果有多个子节点,数据类型就是array 。所以,处理this.props.children 的时候要小心。

React 提供一个工具方法React.Children 来处理this.props.children 。我们可以用React.Children.map 来遍历子节点,而不用担心this.props.children 的数据类型是undefined 还是object


props跟state的区别:this.props表示那些一旦定义,就不再改变的特性,而 this.state是会随着用户互动而产生变化的特性。


组件的生命周期分成三个状态:

  • Mounting:已插入真实 DOM
  • Updating:正在被重新渲染
  • Unmounting:已移出真实 DOM

React 为每个状态都提供了两种处理函数,will函数在进入状态之前调用,did函数在进入状态之后调用,三种状态共计五种处理函数。

  • componentWillMount()
  • componentDidMount()
  • componentWillUpdate(object nextProps, object nextState)
  • componentDidUpdate(object prevProps, object prevState)
  • componentWillUnmount()

此外,React 还提供两种特殊状态的处理函数。

  • componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用
  • shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用






0 0
原创粉丝点击