React中文教程 - Advanced Components(组件高级使用)
|
所谓高级组件均继承ReactCompositeComponent类,ReactCompositeComponent提供一套完善的预处理函数,使用它可以简易的部署很多功能。
1. 生命周期函数下面按照组件的生命周期顺序说明组件的预处理函数 解释不是很全面,注意看函数的名字,“Will”代表“将”,“Did”代表“已经”
1.1 Mounting 添加组件getInitialState(): object 这个函数返回state的object类型值,在renderComponent()之前被调用; componentWillMount()在renderComponent()之前被调用; componentDidMount(DOMElement rootNode)在renderComponenet()之后被调用;
1.2Updating 更新组件componentWillReceiveProps(object nextProps)在renderComponent()之后被调用; shouldComponentUpdate(object nextProps,object nextState): boolean在组件render()之前被调用; componentWillUpdate(object nextProps,object nextState)在组件render()之前被调用; componentDidUpdate(object prevProps,object prevState,DOMElement rootNode)组件render()后被调用;
1.3 Unmounting 移除/释放组件componentWillUnmount() 在unmountAndReleaseReactRootNode()之前被调用; unmountAndReleaseReactRootNode()的功能是释放组件;
2. 公共函数getDOMNode(): DOMElement 可以在componentDidMount()函数内部调用; forceUpdate()当您不使用this.setState()修改私有变量的时候,您可以使用该函数促使render()函数的执行;
3. 组件引用很多情况下,render()返回的是一段HTML代码(含有多标签/DOM),我们需要获取DOM并且使用它。 /** @jsx React.DOM */
var SearchForm = React.createClass({
render: function() {
// 这个例子返回一个Form表单
return (
<form action={this.props.action}>
<input type="search" placeholder="Search..." />
</form>
);
},componentDidMount: function(rootNode) {
// 当表单被render()返回后,这个函数就会被执行,参数rootNode代表返回值当中的根节点(本例的根节点是Form)
// 获取根节点的第一个子节点(即是input),并且让input获取焦点
var searchInput = rootNode.firstChild;
searchInput.focus();
}
});
上例中虽然能正常获取所有的节点,但层次多的时候难免比较困难。我们再来看看React提供的一个更便利的方法
Refs(引用)
/** @jsx React.DOM */
var SearchForm = React.createClass({
render: function() {
// 这个例子返回一个Form表单
return (
<form action={this.props.action}>
<input type="search" placeholder="Search..." ref="searchInput" />
</form>
);
},componentDidMount: function(rootNode) {
// 使用this.refs.[ref的属性值].getDOMNode()获取render返回值中的input标签
var searchInput = this.refs.searchInput.getDOMNode();
searchInput.focus();
}
});
您可以修改并重新发布本文,如果您能留下本文的参考连结,万分谢谢! 如果您对本文存在疑问,欢迎留言或者直接对本文评论,我会在看到的第一时间回复您。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
