不要扩展React.Component [英] do not extend React.Component

查看:405
本文介绍了不要扩展React.Component的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于创建React组件的es6语法是 export default class ExampleComponent extends React.Component 。但是当导出默认类ExampleComponent without extends React.Component 条件是 import'从'react'导入;为什么会发生这种情况

the es6 syntax for creating React component is export default class ExampleComponent extends React.Component.However it still work when export default class ExampleComponent without extends React.Component on condition that import React from 'react'; why this happen

推荐答案

很容易在这种情况下,想念发生什么,但差异真的很大:没有扩展React .Component,你只是创建一个JS类。此外:

It's easy to be in this situation and miss what's happening, but the difference is really huge: without extending React.Component, you're just creating a JS class. Furthermore:


  • 因为它满足了一个React类的要求(可以使用 React.createClass )或作为ES6类),它仍然会工作,

  • 您不会得到lifeCyle方法或访问状态(有人纠正我,如果我错了这个,很肯定你不会只用一个类bc,没有附加的实例)。

  • 这些更简单的组件是一般来说,快速处理和要求更少的机械,因为它们只是一个(希望的)纯粹的功能,呈现出一些东西。

  • 所以,他们的主要区别在于一个具有渲染方法的类,你不是需要。这应该是时间上最多的您不需要访问状态的一切

  • because it satisfies the requirements of a React Class (which you can create with either React.createClass() or as an ES6 class), it'll still "work",
  • but you won't get lifeCyle methods or access to state (someone correct me if I'm wrong about this, pretty certain you wouldn't with just a class bc there's no backing instance attached).
  • these "simpler" components are generally faster for React to deal with and require less "machinery", since they're just a (hopefully) pure function that renders something.
  • so, they key difference here is that with just a class that has a render method you're not "requiring" as much. this should be enough most of the time; you shouldn't need access to state for everything

希望有帮助!

这篇关于不要扩展React.Component的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆