码迷,mamicode.com
首页 > Web开发 > 详细

React文档(二十)不使用JSX

时间:2017-03-01 16:33:27      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:lin   null   targe   需求   ons   log   extend   语法糖   creat   

JSX并不是使用React的一个强制需求。当你不需要在你的构造环境里设置编译那么不使用JSX会很方便。

每一个JSX元素只是调用React.createElement(componnet, 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‘)
);

如果你好奇想看更多的例子JSX被转变成js,你可以试一试在线Babel编译器

组件要么被提供为一个字符串,要么是一个React.Component子类,要么是一个无状态组件的函数。

如果你已经厌倦了React.createElement方法,一个普通模式是使用简写:

const e = React.createElement;

ReactDOM.render(
  e(‘div‘, null, ‘Hello World‘),
  document.getElementById(‘root‘)
);

如果你对React.createElement使用这种简写,那么在不使用JSX语法也一样方便。

React文档(二十)不使用JSX

标签:lin   null   targe   需求   ons   log   extend   语法糖   creat   

原文地址:http://www.cnblogs.com/hahazexia/p/6484427.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!