JSX 与 react 元素

1
const element = <h1>Hello, world!</h1>;

它被称为 JSX,是一个 JavaScript 的语法扩展。JSX 可以生成 React “元素”。实际 react 元素就是 javascript 对象,jsx 返回的就是 javascript 对象。

Babel 会把 jsx 转译成React.createElement()函数调用。
babel 测试地址

1
2
3
4
5
6
7
8
9
10
11
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
//编译后:
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);

最终创建了一个类似这样的对象:

1
2
3
4
5
6
7
8
// 注意:这是简化过的结构
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
};

这些对象就被称为’react 元素’。元素是构成 react 应用的最小砖块,而组件又是由元素构成的。

组件

组件又分为:

  • 函数组件
  • class 组件
1
2
3
4
5
6
7
8
9
10
11
// 函数组件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

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

函数组件与类组件有什么不同呢?

  1. 函数组件写法简洁,接收外部传入的 props,返回对应的 ui
  2. 类组件可以使用生命周期函数,维护自身状态(state)

其实函数组件还可以称为无状态组件。
什么是无状态组件呢?无状态组件内部不使用 state,只根据外部组件传入的 props 返回待渲染的 react 元素。有状态组件则是根据自身的 state 以及外部的 props 来共同决定返回的 react 元素。如此定义的话,类组件则既可以充当无状态组件,也可以充当有状态组件。