Have you wondered how to create a component in React?

您是否想过如何在React中创建组件?

To answer, it is as simple as creating a function returning an HTML-like syntax.

要回答这个问题,就像创建一个返回类似HTML语法的函数一样简单。

import React from 'react';function Counter({n}) {return (<div>{n}</div>);
}export default Counter;

Now let’s see what happened in the code above.  Counter is a function that transforms a number into HTML. And if you look more carefully, Counter is a pure function. That’s right, the kind of function that returns the result based on its inputs and has no side-effects.

现在,让我们看看上面的代码中发生了什么。 Counter是将数字转换为HTML的功能。 而且,如果您仔细一点看, Counter就是一个纯函数。 没错,这种函数会根据输入结果返回结果,并且没有副作用。

This explanation comes with a new question. What is a side-effect?

该解释带有一个新问题。 什么是副作用?

In short, a side-effect is any modification on the environment outside the function or any read information from the outside environment that can change.

简而言之,副作用是对功能外部环境的任何修改或从外部环境读取的任何信息都可能发生变化。

You may have noticed that I used the destructuring assignment syntax in the parameter list to extract out the n input number. That’s because components take as input a single object called “props” that has all the properties sent to them.

您可能已经注意到,我在参数列表中使用了分解分配语法来提取n输入数字。 这是因为组件将一个名为“ props”的对象作为输入,该对象具有发送给它们的所有属性。

Here is how the n parameter can be set from any other component:

这是可以从任何其他组件设置n参数的方法:

<Counter n={1} />

In a sense, this syntax can be imagined like a function call Counter({n: 1}). Isn’t that right?

从某种意义上讲,可以将这种语法想象为函数调用Counter({n: 1}) 。 是不是?

Let’s continue our journey.

让我们继续前进。

Can functional components have state? As the component name suggested I want to store and change a counter. What if we just declare a variable holding a number inside the component? Will it work?

功能组件可以有状态吗? 如组件名称所示,我想存储和更改计数器。 如果我们仅声明一个在组件内部包含数字的变量该怎么办? 能行吗

Let’s find out.

让我们找出答案。

I will start by declaring the variable inside the functional component.

我将从在功能组件内部声明变量开始。

import React from 'react';function Counter() {let n = 0;return (<div>{n}</div>);
}export default Counter;

Now let’s add the function that increments the number and logs it to the console. I will use the function as the event handler for the click event.

现在,让我们添加增加数字的功能并将其记录到控制台。 我将使用该函数作为click事件的事件处理程序。

import React from 'react';function Counter() {let n = 0;function increment(){n = n + 1;console.log(n)}return (<div><span>{n}</span><button onClick={increment}>Increment </button></div>);
}export default Counter;

If we look at the console we see that the number is actually incremented, but that is not reflected on the screen. Any ideas?

如果我们查看控制台,则会看到该数字实际上是递增的,但是并没有反映在屏幕上。 有任何想法吗?

You got it right … we need to change the number, but we need also to re-render it on the screen.

您说对了...我们需要更改数字,但我们还需要在屏幕上重新渲染它。

Here is where the utility function from React Hooks comes into play. By the way, these utility functions are called hooks and they start with the word “use”. We are going to use one of them, useState. I will log also the “re-render” text to console to see how many times the Counter function is actually called.

这是React Hooks的实用程序功能发挥作用的地方。 顺便说一下,这些实用程序功能称为挂钩,它们以单词“ use”开头。 我们将使用其中之一useState 。 我还将记录“重新渲染”文本到控制台,以查看Counter函数实际被调用了多少次。

import React, { useState } from 'react';function Counter() {const [n, setN] = useState(0);console.log('re-render');function increment(){setN(n + 1);console.log(n)}return (<div><span>{n}</span><button onClick={increment}>Increment </button></div>);
}export default Counter;

Let’s read what useState() does.

让我们阅读useState()作用。

What does useState return? It returns a pair of values: the current state and a function that updates it.

什么 useState 回报? 它返回一对值:当前状态和更新状态的函数。

In our case n is the current state and setN() is the function that updates it. Have you checked the console to see how many times the “re-render” text is displayed? I will leave that for you to find out.

在我们的例子中, n是当前状态,而setN()是更新状态的函数。 您是否检查过控制台以查看“重新渲染”文本显示了多少次? 我将其留给您查找。

We can update the state not only by setting the new value but also by providing a function that returns the new value.

我们不仅可以通过设置新值来更新状态,还可以通过提供返回新值的函数来更新状态。

In our case, the function that provides the new value will be called increment(). As you see, increment() is a pure function.

在我们的例子中,提供新值的函数将称为increment() 。 如您所见, increment()是一个纯函数。

import React, { useState } from 'react';function increment(n){return n + 1;
}function Counter() {const [n, setN] = useState(0);return (<div><span>{n}</span><button onClick={() => setN(increment)}>Increment </button></div>);
}export default Counter;

To understand what setN(increment) does, let’s read the documentation.

要了解setN(increment)作用,请阅读文档。

Passing an update function allows you to access the current state value inside the updater.

传递更新功能使您可以访问更新程序中的当前状态值。

OK so increment() gets called with the current n state and it is used to compute the new state value.

好的,所以使用当前的n状态调用increment() ,并将其用于计算新的状态值。

最后的想法 (Final Thoughts)

Let’s summarize what we found out.

让我们总结一下我们发现的结果。

In React we can simply define a component using a function that returns an HTML-like syntax.

在React中,我们可以简单地使用返回类似于HTML语法的函数来定义组件。

React Hooks enables us to define state into such functional components.

React Hooks使我们能够将状态定义为此类功能组件。

And last but not least, we finally got rid of this pseudo-parameter in components. Maybe you have noticed that this becomes annoying by changing context when you don't expect it. No worries about that. We are not going to use this in functional components.

最后但并非最不重要的一点是,我们终于摆脱了组件中的this伪参数。 也许你已经注意到, this成为通过不断变化的环境,当你不指望它烦人。 不用担心。 我们不会在功能组件中使用this

If you've made it this far you can also take a look at my books.

如果到目前为止,您也可以看看我的书。

Discover Functional JavaScript was named one of the best Functional Programming books by BookAuthority!

发现功能JavaScript被称为 BookAuthority最好的函数式编程书籍

For more on applying functional programming techniques to React take a look at Functional React.

有关将函数式编程技术应用于React的更多信息,请查看Functional React 。

Learn functional React, in a project-based way, with Functional Architecture with React and Redux.

通过带有React和Redux的功能架构 ,以基于项目的方式学习功能性React

Tweet me your feedback.

向我发送您的反馈 。

翻译自: https://www.freecodecamp.org/news/a-few-questions-on-functional-components/

如何在React中使用功能组件相关推荐

  1. 如何在React中从其父组件更改子组件的状态

    by Johny Thomas 约翰尼·托马斯(Johny Thomas) 如何在React中从其父组件更改子组件的状态 (How to change the state of a child com ...

  2. 如何在React中做到jQuery-free

    前言 前些天在订阅的公众号中看到了以前阮一峰老师写过的一篇文章,「如何做到 jQuery-free?」.这篇文章讨论的问题,在今天来看仍不过时,其中的一些点的讨论主要是面向新内核现代浏览器的标准 DO ...

  3. react 中渲染html_如何在React中识别和解决浪费的渲染

    react 中渲染html by Nayeem Reza 通过Nayeem Reza 如何在React中识别和解决浪费的渲染 (How to identify and resolve wasted r ...

  4. react网格生成_如何在React中构建实时可编辑数据网格

    react网格生成 by Peter Mbanugo 彼得·姆巴努戈(Peter Mbanugo) 如何在React中构建实时可编辑数据网格 (How to Build a Real-time Edi ...

  5. boost::unorder_map如何插入元素_「React」如何在React中优雅的实现动画

    最简单的动画组件实现 动画的本质,无非就是一个状态样式到另一个状态样式的过渡.最简单的动画组件,我们只需要指定两个状态的样式(进入的样式,离开的样式),以及一个开关(控制状态),即可完成. codep ...

  6. 如何在React中使用gRPC-web

    by Mohak Puri 由Mohak Puri 如何在React中使用gRPC-web (How to use gRPC-web with React) For the past few mont ...

  7. react中创建一个组件_如何使用React和MomentJS创建一个Countdown组件

    react中创建一个组件 Recently I had to create a Countdown for one of my other projects, and I thought that i ...

  8. 如何在React中引入阿里图标库的图标

    一.周所周知 在 Antd Design 中也有一些图标,但是要找到自己想要的图标不是很方便,需要一个一个的找.而且提供的图标数量也不是很多! 而阿里图标库可以通过搜索找到自己想要的图标,图标的数量和 ...

  9. 如何在React中使用Typescript

    TypeScript can be very helpful to React developers. TypeScript对React开发人员可能非常有帮助. In this video, Ben ...

最新文章

  1. HALCON表面划痕检测
  2. VR眼镜,怎样才算性感?
  3. OpenCV3.0中的图像金字塔与图片尺寸缩放
  4. Bootstrap分页
  5. MVC应用程序显示RealPlayer(rm)视频
  6. 主角的创建与选择 Learn Unreal Engine (with C++)
  7. 随想录(三言两语app)
  8. Deepin 系统下安装VMware并激活
  9. 机器学习 深度学习 ai_人工智能,机器学习和深度学习。 真正的区别是什么?...
  10. zipf定律与相似性度量
  11. 怎样png转jpg还可以保持原有大小?
  12. CF1528B Kavi on Pairing Duty(dp)
  13. 基于SSM小区物业管理系统
  14. Android免打包多渠道统计如何实现?通用流行框架大全
  15. Formal Verification (一) 形式验证的分类、发展、适用场景
  16. EXT前端数据传不到后台
  17. ADSL 登陆账号密码嗅探器
  18. 中国书法家协会理事、陕西武警总队原司令员王春新莅临秦储指导交流
  19. 【LeetCode】【剑指offer】【剪绳子(二)】
  20. 中通新财报:业绩下滑背后仍是老问题

热门文章

  1. 【今日CV 计算机视觉论文速览】 25 Feb 2019
  2. Linux 下Kill多进程的方法
  3. 对象交互 模拟顾客点菜 c# 1614008435
  4. 案例 项目经理评分 c# 1613922661
  5. python 列表数据类型 200221
  6. linux通过bg后台执行作业
  7. oracel 创建视图给某个用户
  8. 区块链开发公司 注重用户的价值才是企业归宿
  9. 070——VUE中vuex之使用getters计算每一件购物车中商品的总价
  10. 2017年国内开源镜像站点汇总