react 细节整理

前言:

  在使用react时针对于其的大面的语法,规范等是有了解的,可能会忽略了些细节的东西导致在调试的时候会很麻烦,今天我将针对其中的细节点进行下整理,希望能够让大家更加深入,全面地地去了解react。

细节

  1. 组件类的render中只能包含一个顶级标签

  // 错误写法
  var ErrorComponent = React.createClass({
      render: function() {
          return  <span>test1</span>
                  <span>test2</span>;
      }
  })
  // 正确写法
  var SuccessComponent = React.createClass({
      render: function() {
          return
              <div>
                  <span>test1</span>
                  <span>test2</span>
              </div>;
      }
  })

  2. 两个特殊属性: 由于class和for是js的关键字,故此class->className  for->htmlFor 

  3. this.props可以一一获取其对应的组件的属性值,但是有一特殊值-this.props.children(表示组件的子节点),不同情况返回不同类型的值

     3.1 undefined: 无子节点

     3.2 object:只有一个子节点

     3.3 array: 两个及以上子节点

    有人说了使用这个属性太麻烦了,还需要判断类型。。答案是否定的。。react提供了React.Children的工具方法来处理this.props.children的属性值

var SuccessComponent = React.createClass({
    render: function() {
        return (
            <ul>
                {
                    React.Children.map(this.props.children, function (dom) {
                        return <li>{dom}</li>;
                    })
                }
            </ul>
        );
    }
});

ReactDOM.render(
    <SuccessComponent>
        <span>test1</span>
        <span>test2</span>
        <span>test3</span>
    </SuccessComponent>,
    document.body
);

  4.ref

    前言: 组件并不是真实的DOM,而是存在于内存中的数据结构-虚拟DOM,  只有当插入到文档中才会形成真实的DOM,所有DOM的改动都会先更新虚拟DOM之后再根据具体的变化更新到对应的真实DOM上

    作用: ref用于引用真实DOM,因此必须保证操作this.refs.[refName]的时候必须保证虚拟DOM插入到文档中才可使用

var FormComponent = React.createClass({
    focusUserName: function () {
        this.$refs.userName.focus();
    },
    render: function() {
        return (
            <div>
                <input type="text" name="userName" ref="userName" />
                <button onClick={this.focusUserName}></button>
            </div>
        );
    }
});

   5. this.props和this.state都能表示组件的属性,它们是有区别的

    使用上:  this.props的属性的值是无法修改的, this.state是可以任意修改的

    默认值:  getDefaultProps方法用于返回默认props

        getInitialState方法用户返回默认state

  6. 生命周期

    6.1 阶段:

      Mounting: 已渲染真实DOM

      Updating: 正在被重新渲染

      Unmounting: 已移除DOM

    6.2 阶段事件

      componentWillMount(): 渲染真实DOM前

      componentDidMount(): 渲染真实DOM后

      componentWillUpdate(object nextProps, object nextState): 重新渲染前

      componentDidUpdate(object prevProps, object prevState): 重新渲染后

      componentWillUnmount(): 移除DOM前

    6.3 状态事件

      componentWillReceiveProps(object nextProps): 组件接受新的参数

      shouldComponentUpdate(object nextProps, object nextState): 组件是否需要重新渲染时调用

谢谢客官的品尝,如有不严谨和错误地方请希望指正,祝大家工作和生活顺利 !

    

  

  

原文地址:https://www.cnblogs.com/yincece0316/p/12594752.html