简体   繁体   English

React Components - 创建它们的正确方法是什么?

[英]React Components - What is the proper way to create them?

I'm learning React and I came across two different ways to create components.我正在学习 React,我遇到了两种不同的创建组件的方法。 One is by Facebook and the other by AirBnB .一个是Facebook的,另一个是AirBnB的。 I also saw them in the tutorials I've been watching.我还在我一直在看的教程中看到了它们。

This may be a stupid question, but which one is better?这可能是一个愚蠢的问题,但哪个更好?

Facebook: Facebook:

var React = require("react");

var Component = React.createClass({
    render: function(){
        return (
            <div>{this.props.item}</div>
        );
    }
});

module.exports = Component;

AirBnB:民宿:

import React from "react";

export default class Component extends React.Component {
    render() {
        return (
            <div>{this.props.item}</div>
        );
    }
}

Disclaimer: I may have errors in the code, so please forgive me and just focus on the style.免责声明:我可能在代码中有错误,所以请原谅我,只关注样式。

React components:反应组件:

You have 4 basic ways of creating a reusable React component :您有 4 种创建 可重用 React 组件的基本方法:

  • Function components using const MyComponent = () => {} or function MyComponent() + Hooks - The current standard of creating react components.使用const MyComponent = () => {}function MyComponent() + Hooks的函数组件 - 创建反应组件的当前标准。 The component is a function that returns the JSX to render.该组件是一个返回要渲染的 JSX 的函数。 Hooks replace the life-cycle methods of the class components.钩子取代了类组件的生命周期方法。

  • class MyComponent extends React.Component {} - the ES6 way of creating a stateful component. class MyComponent extends React.Component {} - ES6 创建有状态组件的方式。 Requires transpiling via babel, which also handles JSX.需要通过 babel 进行转译,它也处理 JSX。 If you need state, and lifecycle methods - use this.如果您需要状态和生命周期方法 - 使用它。

  • class MyComponent extends React.PureComponent {} - new in React 15.3.0 . class MyComponent extends React.PureComponent {} - React 15.3.0中的新功能。 Same as React.Component, but with a PureRenderMixin like functionality, since ES6 components don't support mixins.与 React.Component 相同,但具有类似PureRenderMixin的功能,因为 ES6 组件不支持 mixin。

  • React.createClass({}) - the old way, doesn't require transpiling, but since you'll probably use JSX, you'll need transpiling anyway. React.createClass({}) - 旧方法,不需要转译,但由于您可能会使用 JSX,所以无论如何您都需要转译。 Still appears in old React tutorials, but will be deprecated eventually.仍然出现在旧的 React 教程中,但最终会被弃用。

JS modules: JS模块:

Nodejs syntax (commonjs) uses require() and ES6 uses import . Nodejs 语法(commonjs)使用require()而 ES6 使用import You can use whatever you like, and even mix the two, but the ES6 modules way of import/exporting is a bit more 'standard' for react components.你可以使用任何你喜欢的东西,甚至将两者混合使用,但是 ES6 模块的导入/导出方式对于反应组件来说更“标准”。 For now import is actually transpiled by babel to require anyway.现在import实际上被 babel 转译为require Both require and import need some sort of a bundling tool, such as webpack or browserify to work in a browser. requireimport都需要某种捆绑工具,例如 webpack 或 browserify 才能在浏览器中工作。

render() vs .render:渲染()与 .render:

The render() is the ES6 way of defining a method in ES6 classes. render()是在 ES6 类中定义方法的 ES6 方式。

React.createClass({}) requires a JS object literal. React.createClass({})需要一个 JS 对象字面量。 In ES5, defining methods in object literals uses the prop: function() {} syntax, such as render: function() syntax.在 ES5 中,在对象字面量中定义方法使用prop: function() {}语法,例如render: function()语法。 btw - In ES6 you can actually write the method in the literal as render() instead.顺便说一句 - 在 ES6 中,您实际上可以将文字中的方法编写为render()

The one from AirBnB uses an ES6 way but would require a transpiler like Babel.来自 AirBnB 的那个使用 ES6 方式,但需要像 Babel 这样的转译器。

ES6 is the next revision of the Javascript language ES6 是 Javascript 语言的下一个版本

Read more: https://toddmotto.com/react-create-class-versus-component/阅读更多: https ://toddmotto.com/react-create-class-versus-component/

As they say there is more than one way to skin a cat.正如他们所说,给猫剥皮的方法不止一种。 As it happens, there is also more than one way to create a React component, which is much more animal friendly!碰巧,创建 React 组件的方法也不止一种,它对动物更友好!

When React was initially released, there was no idiomatic way to create classes in JavaScript, so 'React.createClass' was provided.当 React 最初发布时,没有在 JavaScript 中创建类的惯用方法,因此提供了“React.createClass”

Later, classes were added to the language as part of ES2015, where the ability to create React components using JavaScript classes was added.后来,类作为 ES2015 的一部分被添加到该语言中,其中添加了使用 JavaScript 类创建 React 组件的能力。 Along with functional components , JavaScript classes are now the preferred way to create components in React.除了函数式组件,JavaScript现在是在 React 中创建组件的首选方式。

For existing 'createClass' components, it is recommended that you migrate them to JavaScript classes.对于现有的“createClass”组件,建议您将它们迁移到 JavaScript 类。 However, if you have components that rely on mixins, converting to classes may not be immediately feasible.但是,如果您有依赖于 mixin 的组件,则转换为类可能不会立即可行。 If so, create-react-class is available on npm as a drop-in replacement.如果是这样,可以在 npm 上使用 create-react-class 作为替代品。

The simplest version of React component is a plain JavaScript function that returns a React element: React 组件的最简单版本是一个普通的 JavaScript 函数,它返回一个 React 元素:

Functional components:功能组件:

function Label() {
  return <div>Super Helpful Label</div>
}

Of course with the wonders of ES6 we can just write this as an arrow function.当然,有了 ES6 的奇迹,我们可以把它写成一个箭头函数。

const Label = () => <div>Super Helpful Label</div>

These are used like this:这些是这样使用的:

const Label = () => <div>Super {props.title} Helpful Label</div>

class App extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <div>
         <Label title="Duper" />
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

With functions you can also destructure the properties in the function signature.使用函数,您还可以解构函数签名中的属性。 It saves you from having to write props over and over again.它使您不必一遍又一遍地编写道具。

Components can also be ES6 classes.组件也可以是 ES6 类。 If you want your component to have local state then you need to have a class component.There are also other advantages to classes such as being able to use lifecycle hooks and event handlers.如果您希望您的组件具有本地状态,那么您需要有一个类组件。类还有其他优点,例如能够使用生命周期挂钩和事件处理程序。

Class components:类组件:

class Label extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return <div>Super {this.props.title} Helpful Label</div>
  }
}

class App extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
      <div>
        <Label title="Duper" />
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

There are pros and cons in both styles but functional components are taking over modern React in the foreseeable future.这两种风格各有利弊,但功能组件在可预见的将来会取代现代 React。

A functional component is written shorter and simpler, which makes it easier to develop, understand, and test.功能组件编写得更短更简单,这使得开发、理解和测试更容易。
Class components can be confusing with so many uses of this .类组件可能会与this的许多用途混淆。 Using functional components can easily avoid this kind of mess and keep everything clean.使用函数式组件可以轻松避免这种混乱并保持一切清洁。

React team is supporting more React hooks for functional components that replace or even improve upon class components. React 团队正在为功能组件支持更多的 React 钩子,以替换甚至改进类组件。 React team mentioned in earlier days that they will make performance optimizations in functional components by avoiding unnecessary checks and memory allocations. React 团队早些时候提到,他们将通过避免不必要的检查和内存分配来对功能组件进行性能优化。
And as promising as it sounds, new hooks are recently introduced for functional components such as useState or useEffect while also promising that they are not going to obsolete class components .尽管听起来很有希望,但最近为诸如useStateuseEffect 之类的功能组件引入了新的钩子,同时还承诺它们不会过时类组件 The team is seeking to gradually adopt functional components with hooks in newer cases, which means that there is no need to switch over the existing projects that utilize class components to the entire rewrite with functional components so that they can remain consistent.团队正在寻求在较新的案例中逐步采用带有钩子的功能组件,这意味着无需将现有的使用类组件的项目切换到使用功能组件进行整体重写,从而保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建可重用组件的正确方法是什么? - What is the proper way to create reusable components react 基于 redux 状态控制反应组件的正确方法是什么 - What is the proper way to control react components based on redux state 在React中组件之间传递依赖关系的正确方法是什么? - What's the proper way to pass dependencies between components in React? 什么是从React中从同一文件导入多个组件的正确方法,而不是导入每个组件 - what is proper way to import multiple components from same file in react instead of getting each component imported React 兄弟组件之间交换对象的正确方式 - The proper way of exchanging objects between sibling components in React 在两个反应组件之间设置状态的正确方法 - Proper way to set state between two react components 反应高阶组件:添加实例方法的正确方法 - React Higher Order Components: Proper way to add instance methods 在 React 中使用 Hooks 获取 JSON 的正确方法是什么? - What is the proper way to fetch JSON in React with Hooks? 使用 React Hooks 设置 state 的正确方法是什么? - What is the proper way to set state with React Hooks? 构建React 0.12项目的正确方法是什么? - What is the proper way to build a React 0.12 Project?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM