如何在React中使用功能组件

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值