当我们了解了一些React基本概念后,我们就可以尝试创建一个简单的React 应用。
创建一个React应用。创建一个React应用仅仅需要三步;
- 定义一个React Element
- 从DOM上获取一个节点
- 将React Element挂载到获取的节点上
用代码展示一下
1 | import react from 'React'; |
我们可以通过代码看到,第一行引入了react,但在下面的代码中并没有使用。但又必须得引入,这是为什么呢?大家应该都知道React中有一个JSX的概念。我们下面的reactElement其实就是通过JSX来定义的。
JSX是一个语法糖。可以用工具将它转为普通的JavaScript(如Babel)从而让浏览器正确的解析他。这个转换的过程非常简单。其实它就是通过调用react中的createElement传入一些参数(如标签名、props、children),从而返回一个对象。我们来手动的转换一下。1
2
3
4
5const reactElement = React.createElement(
"div", //标签名
{ title: 'hello' }, //props 我们可以给这个Element传一个title
"Hello React" // 这个元素的 children
)
React.createElement 它不光会创建一个对象,还会做一些验证。比如将字符串变量进行转义,从而防止XSS攻击。
返回的对象是什么呢? 我们可以暂且认为返回的是一个包含type和props的对象。真实返回的对象不只有这两个属性。我们现在只需要关注这两个属性即可。1
2
3
4
5
6
7const reactElement = {
type: 'div',
props: {
title: 'hello',
children: 'Hello React'
}
}
这个对象中type就是指定要创建DOM元素的标签名,props对象上存的是JSX上的所有属性,还有一个就是chlidren存的是JSX中的子元素。可以是string也可以是Element数组。
第二行获取一个DOM元素,本身就是JavaScript代码。这部分不需要多说。
我们看看下面这行代码ReactDOM.render(reactElement, root)
我们来自己实现一下render方法。
我们先通过type创建一个DOM元素。并将所有属性赋给这个元素。
const node = document.createElement(reactElement.type);
node["title"] = reactElement.props.title
然后我们再创建子元素。我们这个例子是一个string,我们就简单地创建一个text node
const text = document.createTextNode("")
text["nodeValue"] = reactElement.props.children
最后将textNode添加到div上,然后再将div加到root上。
node.appendChild(text)
root.appendChild(node)
最后我们看下完整代码:
const reactElement = {
type: 'div',
props: {
title: 'hello',
children: 'Hello React'
}
}
const root = document.getElementById('root');
const node = document.createElement(reactElement.type);
node["title"] = reactElement.props.title;
const text = document.createTextNode("");
text["nodeValue"] = reactElement.props.children;
node.appendChild(text);
root.appendChild(node);
至此,我们就完全搞清楚了如何创建React应用。以及如何不用React创建一个一模一样的简单应用。