React进阶笔记7(不使用JSX)
2018-08-15 本文已影响0人
XKolento
不使用jsx
在编写React的时候,jsx并不是必选的,当你不想在你的构建环境中安装相关编译工具的时候,不使用jsx编写React反而会比较方便。
每一个jsx元素都只是React.createElement(component,props,...children)
的语法糖。
因此任何时候你写的jsx语法都可以使用js写出来。
比如下面这段代码是使用jsx实现的:
class Hello extends React.Component{
render(){
return <div>hello {this.props.toWhat}</div>
}
}
ReactDOM.render(
<Hello toWhat="world" />,document.getElementById('root')
)
以上的代码可以编译为以下不使用jsx的代码
class Hello extends React.Component{
render(){
return React.createElement(
'div',
null,
`hello, ${this.props.toWhat}`
)
}
}
ReactDOM.render(
React.createElement(
Hello,{toWhat:'world!!!'},null
),
document.getElementById('root')
)
简单的demo展示jsx与js之间的转换:
function hello() {
return <div class="test">Hello world!</div>;
}
function world(){
return <p id="test2" userid="123">react</p>
}
以上的2个组件转化后:
"use strict";
function hello() {
return React.createElement(
"div",
{ "class": "test" },
"Hello world!"
);
}
function world() {
return React.createElement(
"p",
{ id: "test2", userid: "123" },
"react"
);
}
如果你很好奇想了解更多关于JSX如何被转化为 JavaScript 的例子,你可以尝试下这个在线Babel编译器。
一个组件可以是一个字符串,或者也是可以是React.Component的子类,当组件是无状态组件的时候,他可以是一个函数。
如果你对每次都要输入React.createElement()
感到非常厌烦的话,以下是一种常用的简写方式。
等于就是变量替换。
const e = React.createElement;
ReactDOM.render(
e('div',null,'hello world'),
document.getElementById('root')
)
如果你使用React.createElement
的简写形式,这样会很方便去编写不使用JSX的React应用。
其他选择的话,你可以去参考社区上的项目例如react-hyperscript
和 hyperscript-helpers
。它们都提供了一些简洁的语法。