ReactJS学习笔记系列。

React Component

React的网站有丰富的文档,特别是Getting Started部分。其中的MAIN CONCEPTS部分解释了React的主要概念,要熟练使用React,这些概念必须熟练掌握。

React就是JavaScript

第一个必须牢记的概念是React就是JavaScript。

对于下面这个React程序:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

上面的代码经过bable转译以后,就变成:

class Welcome extends React.Component {
  render() {
    return React.createElement(
      "h1",
      null,
      "Hello, ",
      this.props.name
    );
  }
}

这部分代码JSX代码<h1>Hello, {this.props.name}</h1>被转译之后,变成了JavaScript表达式,转化了为对React API的调用。

Introducing JSX

React Component和Element

从上一个例子可以看出,JSX主要是一种语法糖,让你以接近HTML的方式来书写React表达式,React并不依赖于JSX。其实,React的两个核心要素是Component和Element。对于React,Component是一部分可以重用的代码,它可以是一个带有render()方法的类,像class Welcome extends React.Component {...}那样,render()会返回一个React Element;或者Component可以直接是一个函数,返回React Element。

React Element则跟HTML Element类似,可以以标签的方式出现在JSX中:

<div>
  <Welcome/>
</div>

在上面的JSX片段中,div是一个HTML Element,而Welcome是一个自定义的React 元素。

和HTML Element一样,React Element支持把代码逻辑嵌在标记中;和HTML Element不一样的是,React Element最终被转化为一个React的API调用,内嵌在React Element中的代码逻辑会转化为API调用的参数。

需要注意的是,在JSX中HTML Element以小写字母开头,而React Element以大写字母开头

React Component可以返回null,也就是返回一个空的React Element,那么这个Component可以说是Renderless

生成HTML Element需要操作DOM,而React Element是纯JavaScript,总体来看,React Element的开销比较小。

Redering Elements

Component的输入参数props

前面提到React Component是一部分可以重用的代码,调用这部分代码可以生成React Element。其实,React Component还可以接受一个对象props,里面包含针对该Component的输入参数。对于<welcome name="Sara" />这个Component调用而言,它的props是一个包含值为"Sara"的name属性的对象。

props只在生成React Element的时候使用,当一个Element生成以后,它不应该再去修改props。此外,一个Component的输入应该只从props来,而不应该使用其他途径。

为了获得最大的可重用性,一个React Component不应该去修改它的输入props,并且要针对同样的props生成同样的React Element。具有这样特点的React Component可以称为一个pure(纯)的React Component.

Components and Props

(本篇完)