当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 新手学习 React 迷惑的点

新手学习 React 迷惑的点

2019年09月05日  | 移动技术网IT编程  | 我要评论

网上各种言论说 react 上手比 vue 难,可能难就难不能深刻理解 jsx,或者对 es6 的一些特性理解得不够深刻,导致觉得有些点难以理解,然后说 react 比较难上手,还反人类啥的,所以我打算写两篇文章来讲新手学习 react 的时候容易迷惑的点写出来,如果你还以其他的对于学习 react 很迷惑的点,可以在留言区里给我留言。

为什么要引入 react

在写 react 的时候,你可能会写类似这样的代码:

import react from 'react'

function a() {
  // ...other code
  return <h1>前端桃园</h1>
}

你肯定疑惑过,下面的代码都没有用到 react,为什么要引入 react 呢?

如果你把 import react from ‘react’ 删掉,还会报下面这样的错误:

7f6e506e-3025-401d-a492-3b501f8081c6

那么究竟是哪里用到了这个 react,导致我们引入 react 会报错呢,不懂这个原因,那么就是 jsx 没有搞得太明白。

你可以讲上面的代码(忽略导入语句)放到 里进行转化一下,发现 babel 会把上面的代码转化成:

function a() {
  // ...other code
  return react.createelement("h1", null, "前端桃园");
}

因为从本质上讲,jsx 只是为 react.createelement(component, props, ...children) 函数提供的语法糖。

为什么要用 classname 而不用 class

  1. react 一开始的理念是想与浏览器的 dom api 保持一直而不是 html,因为 jsx 是 js 的扩展,而不是用来代替 html 的,这样会和元素的创建更为接近。在元素上设置 class 需要使用 classname 这个 api:

    const element = document.createelement("div")
    element.classname = "hello" 
  2. 浏览器问题,es5 之前,在对象中不能使用保留字。以下代码在 ie8 中将会抛出错误:

    const element = {
      attributes: {
        class: "hello"
      }
    } 
  3. 解构问题,当你在解构属性的时候,如果分配一个 class 变量会出问题:

    const { class } = { class: 'foo' } // uncaught syntaxerror: unexpected token }
    const { classname } = { classname: 'foo' } 
    const { class: classname } = { class: 'foo' } 

其他讨论可见:有趣的话题,为什么jsx用classname而不是class

为什么属性要用小驼峰

因为 jsx 语法上更接近 javascript 而不是 html,所以 react dom 使用 camelcase(小驼峰命名)来定义属性的名称,而不使用 html 属性名称的命名约定。

来自 jsx 简介

为什么 constructor 里要调用 super 和传递 props

这是官网的一段代码,具体见:

class clock extends react.component {
  constructor(props) {
    super(props);
    this.state = {date: new date()};
  }

  render() {
    return (
      <div>
        <h1>hello, world!</h1>
        <h2>it is {this.state.date.tolocaletimestring()}.</h2>
      </div>
    );
  }
}

而且有这么一段话,不仅让我们调用 super 还要把 props 传递进去,但是没有告诉我们为什么要这么做。image-20190901222456704

不知道你有没有疑惑过为什么要调用 super 和传递 props,接下来我们来解开谜题吧。

为什么要调用 super

其实这不是 react 的限制,这是 javascript 的限制,在构造函数里如果要调用 this,那么提前就要调用 super,在 react 里,我们常常会在构造函数里初始化 state,this.state = xxx ,所以需要调用 super。

为什么要传递 props

你可能以为必须给 super 传入 props,否则 react.component 就没法初始化 this.props

class component {
  constructor(props) {
    this.props = props;
    // ...
  }
}

不过,如果你不小心漏传了 props,直接调用了 super(),你仍然可以在 render 和其他方法中访问 this.props(不信的话可以试试嘛)。

为啥这样也行?因为react 会在构造函数被调用之后,会把 props 赋值给刚刚创建的实例对象:

const instance = new yourcomponent(props);
instance.props = props;

props 不传也能用,是有原因的。

但这意味着你在使用 react 时,可以用 super() 代替 super(props) 了么?

那还是不行的,不然官网也不会建议你调用 props 了,虽然 react 会在构造函数运行之后,为 this.props 赋值,但在 super() 调用之后与构造函数结束之前, this.props 仍然是没法用的。

// inside react
class component {
  constructor(props) {
    this.props = props;
    // ...
  }
}

// inside your code
class button extends react.component {
  constructor(props) {
    super(); // 

                    

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网