第一个react程序

一个简单的例子:
index.html
Add React in One Minute
like_button.js
'use strict'; const e = React.createElement; class LikeButton extends React.Component { constructor(props) { super(props); this.state = { liked: false }; }
render() { if (this.state.liked) { return 'You liked this.'; }
return e( 'button', { onClick: () => this.setState({ liked: true }) }, 'Like' ); } }
const domContainer = document.querySelector('#like_button_container'); ReactDOM.render(e(LikeButton), domContainer);
关于上面这段代码的简单解释:
'use strict' 是什么意思?
表示代码在严格模式下运行。
一些在"正常模式"下可以运行的语句,在"严格模式"下将不能运行。比如使用一个未声明的变量,给一个不存在的变量赋值。
具体参考文章 http://www.ruanyifeng.com/blog/2013/01/javascript_strict_mode.html
React.Component 是什么?
React允许您将组件定义为类或函数。要定义React组件类,需要继承React.Component基类
constructor ?
是组件的构造函数,在组件的生命周期中,可以说是最早被调用的。通常用来初始化state,和绑定method
super(props) ?
在为React.Component子类实现构造函数时,应该在任何其他语句之前调用super(props)。否则,this.props在构造函数中将是undefined,这可能导致错误。
this.state ?
State类似于props,但它是私有的并且完全由组件控制。
React.createElement ?
创建并返回一个新的指定类型的react element。用法:
React.createElement( type, [props], [...children] )
ReactDOM.render ?
ReactDOM.render(element, container[, callback])
将React element渲染到提供的容器中的DOM中,并返回对组件的引用。
如果React元素先前已渲染到容器中,则会对其执行更新,并仅在必要时改变DOM以反映最新的element。
如果提供了可选回调,则将在呈现或更新组件后执行该回调。