组件
React 允许将代码封装成组件(component),然后像插入普通 HTML 标签一样,在网页中插入这个组件。
React.createClass 方法用于生成一个组件类,下面代码中变量 PersonName就是一个组件类。
var PersonName = React.createClass({
render: function() {
return <h1>Hello {this.props.name}</h1>;
}
});
ReactDOM.render(
<PersonName name="boyas" />,
document.getElementById('example')
);
this.props.children
this.props 对象的属性与组件的属性一一对应,除了this.props.children 属性——它表示组件的所有子节点。
var NotesList = React.createClass({
render: function() {
return (
<ol>
{
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>;
})
}
</ol>
);
}
});
ReactDOM.render(
<NotesList>
<span>hello</span>
<span>world</span>
</NotesList>,
document.body
);
this.props.children 的值有三种可能:
- 如果当前组件没有子节点,它就是 undefined
- 如果有一个子节点,数据类型是 object
- 如果有多个子节点,数据类型就是 array 。
PropTypes
组件类的PropTypes属性可以验证组件实例的属性是否符合要求,并且getDefaultProps 方法可以用来设置组件属性的默认值。
获取真实的DOM节点
有一种数据结构存在于内存之中,叫做虚拟 DOM (virtual DOM),只有当它插入文档以后,才会变成真实的 DOM —— 组件不是真实的DOM节点。
有时从组件获取真实 DOM 的节点,需要用到 ref 属性,值得注意的是必须等到虚拟 DOM 插入文档以后,才能使用这个属性,否则会报错。
this.state 和this.props区别
- this.props 表示那些一旦定义,就不再改变的特性
- this.state 表示随着用户互动而产生变化的特性。
表单
用户在表单填入的内容不能用 this.props 读取。
组件的生命周期
组件的生命周期分成三个状态:
- Mounting:已插入真实 DOM
- Updating:正在被重新渲染
- Unmounting:已移出真实 DOM
React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数。
- componentWillMount()
- componentDidMount()
- componentWillUpdate(object nextProps, object nextState)
- componentDidUpdate(object prevProps, object prevState)
- componentWillUnmount()
React 还提供两种特殊状态的处理函数:
- componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用
- shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用
Ajax
组件的数据来源,通常是通过 Ajax 请求从服务器获取,可以使用 componentDidMount 方法设置 Ajax 请求,等到请求成功,再用 this.setState 方法重新渲染 UI。