反应:何时使用基于ES6类的组件与功能ES6组件? [英] React: when to use ES6 class based components vs. functional ES6 components?

查看:85
本文介绍了反应:何时使用基于ES6类的组件与功能ES6组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在花了一些时间学习React后,我了解了创建组件的两个主要范例之间的区别。



我的问题是什么时候应该使用哪一个,为什么?



ES6 / 7课程:






  import反应,{Component}来自'react'; 

export class MyComponent extends Component {
render(){
return(
< div>< / div>
);
}
}

功能:






  const MyComponent =(props)=> {
return(
< div>< / div>
);
}

只要没有状态被该组件操纵,我正在思考功能...但是呢?



我猜测如果我使用任何生命周期方法,最好使用基于类的组件。

解决方案

你有正确的想法。去功能,如果你的组件不会做太多,而不是采取一些道具和渲染。您可以将这些视为纯粹的功能,因为它们将始终呈现和表现相同,给予相同的道具。另外,他们不关心生命周期的方法或者有自己的内部状态。



因为它们是轻量级的,将这些简单的组件写成功能组件是非常标准的。 / p>

如果您的组件需要更多功能,例如保持状态,请改用。



更多信息: https://facebook.github.io/react/docs/reusable-components。 html#es6-class


After spending some time learning React I understand the difference between the two main paradigms of creating components

My question is when should I use which one and why? what are the benefits/tradeoffs of one over the other?

ES6/7 classes:


import React, { Component } from 'react';

export class MyComponent extends Component {
  render() {
    return (
      <div></div>
    );
  }
}

Functional:


const MyComponent = (props) => {
    return (
      <div></div>
    );
}

I'm thinking functional whenever there is no state to be manipulated by that component...but is that it?

I'm guessing if I use any life cycle methods, it might be best to go with a class based component.

解决方案

You have the right idea. Go with functional if your component doesn't do much more than take in some props and render. You can think of these as pure functions because they will always render and behave the same, given the same props. Also, they don't care about lifecycle methods or have their own internal state.

Because they're lightweight, writing these simple components as functional components is pretty standard.

If your components need more functionality, like keeping state, use classes instead.

More info: https://facebook.github.io/react/docs/reusable-components.html#es6-classes

这篇关于反应:何时使用基于ES6类的组件与功能ES6组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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