react中不强制使用jsx,但还是推荐使用。在jsx中:
- 把标记与逻辑混在一起
- 属性定义使用小驼峰(camelCase),引号或者花括号包裹
- 用户定义的组件必须大写字母开头
- if 语句以及 for 循环不是 JavaScript 表达式,所以不能在 JSX 中直接使用
- Props 默认值为 “True”
- js表达式作为子元素
- 函数作为子元素
- false, null, undefined, and true 是合法的子元素,但它们并不会被渲染
Babel 会把 JSX 转译成一个名为 React.createElement() 函数调用
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
转成
const element = React.createElement(
'h1',
{className: 'greeting'},
' Hello, world!'
);
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
};
不使用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')
);