React 视浏览器每一个显示的项目为一个组件,组件和组件是一层和一层的调用及嵌套关系。要想在界面上显示你要显示的信息,就先要学会组件的定义。

组件是一个独立的 JavaScript 类,他继承与 React 的 Component。首先我们要 import React 和 Component 模块。随后生成一个类继承 React.Component。并实现一个 render 方法,告诉外界你这个组件绘制了哪些内容。最终在文件底部导出这个模块,提供其他模块导入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 伪代码
import React, { Component } from 'react';

class CommentBox extends React.Component {
render() {
return (
<div className="ui comments">
.....
</div>
);
}
}

export { CommentBox as default };

在 index.js 中引入我们写好的模块需要首先 import 我们编写好的模块。然后直接在 ReactDOM.render 中将我们组件作为第一个参数传递即可。

1
2
3
4
5
6
7
8
import React from 'react';
import ReactDOM from 'react-dom';
import CommentBox from './comment/CommentBox';

ReactDOM.render(
<CommentBox />,
document.getElementById('root')
);

这样我们自己定义的组件就可以显示出来了。