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();
    }
});

您可以修改并重新发布本文,如果您能留下本文的参考连结,万分谢谢! 如果您对本文存在疑问,欢迎留言或者直接对本文评论,我会在看到的第一时间回复您。

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...