Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

无状态函数式组件 #37

Open
hsipeng opened this issue Mar 15, 2018 · 0 comments
Open

无状态函数式组件 #37

hsipeng opened this issue Mar 15, 2018 · 0 comments

Comments

@hsipeng
Copy link
Owner

hsipeng commented Mar 15, 2018

简介

在大部分React代码中,大多数组件被写成无状态的组件,通过简单组合可以构建成其他的组件等;这种通过多个简单然后合并成一个大应用的设计模式被提倡。

形式上表现为一个只带有一个render方法的组件类,通过函数形式或者ES6 arrow function的形式在创建,并且该组件是无state状态的

特点:

  • 组件不会被实例化,整体渲染性能得到提升
    因为组件被精简成一个render方法的函数来实现的,由于是无状态组件,所以无状态组件就不会在有组件实例化的过程,无实例化过程也就不需要分配多余的内存,从而性能得到一定的提升。
  • 组件不能访问this对象
    无状态组件由于没有实例化过程,所以无法访问组件this中的对象,例如:this.ref、this.state等均不能访问。若想访问就不能使用这种形式来创建组件
  • 组件无法访问生命周期的方法
    因为无状态组件是不需要组件生命周期管理和状态管理,所以底层实现这种形式的组件时是不会实现组件的生命周期方法。所以无状态组件是不能参与组件的各个生命周期管理的。
  • 无状态组件只能访问输入的props,同样的props会得到同样的渲染结果,不会有副作用

代码实现

// React.createClass
var Text =  React.createClass({
.....
});

//es5 React.Component
class Text extends React.Component {
  render() {
    return <p>{this.props.children}</p>;
  }
}

//函数式声明组件
const Text = (props) =>
  <p>{props.children}</p>;

补充:

无状态组件内部其实是可以使用ref功能的,虽然不能通过this.refs访问到,但是可以通过将ref内容保存到无状态组件内部的一个本地变量中获取到。
例如下面这段代码可以使用ref来获取组件挂载到dom中后所指向的dom元素:

function TestComp(props){
    let ref;
    return (<div>
        <div ref={(node) => ref = node}>
            ...
        </div>
    </div>)
}

参考

关于react无状态组件(函数式组件)
React创建组件的三种方式及其区别

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant