react hooks使用_如何开始使用React Hooks:受控表格

react hooks使用

by Kevin Okeh

由Kevin Okeh

如何开始使用React Hooks:受控表格 (How to Get Started With React Hooks: Controlled Forms)

React Hooks are a shiny new proposal that will allow you to write 90% cleaner React. According to Dan Abramov, Hooks are the future of React.

React Hooks是一个崭新的提议 ,可以让您编写90%更干净的React。 根据Dan Abramov的说法, Hooks是React的未来。

That sounds good and all but what are Hooks and how will they help me write better code? Glad you asked.

听起来不错,但Hooks到底是什么,它们将如何帮助我编写更好的代码? 很高兴你问。

Hooks allow you to access state and Lifecycle methods in a functional component. If the previous sentence sounds strange to you, then you should refresh your memory of React here.

挂钩允许您访问功能组件中的state和生命周期方法。 如果上一个句子对您来说听起来很奇怪,那么您应该在此处刷新对React的记忆。

The React team says it will help you write clean code without the baggage of Stateful Components. After implementing a barebones form using Hooks, I agree with them.

React团队表示,它将帮助您编写干净的代码,而无需负担Stateful Components。 使用Hooks实现准系统表单后,我同意他们的观点。

Let’s go ahead to code a simple form first in a Stateful Component. We’ll rewrite the same form using Hooks and you can decide which one you like better.

让我们继续先在有状态组件中编写一个简单的表单。 我们将使用Hooks重写相同的表单,您可以决定自己更喜欢哪种表单。

建立 (SETUP)

Head over to codesandbox.io, create an account, sign in, and create a new Sandbox. Select React when creating the Sandbox.

转至codesandbox.io ,创建一个帐户,登录并创建一个新的沙箱。 创建沙箱时选择React。

Now with the Sandbox open, we’ll have to make sure that we use a version of React that has support for Hooks. This is because Hooks are only accessible in Alpha versions for now.

现在打开沙箱,我们必须确保我们使用支持Hooks的React版本。 这是因为钩子目前仅在Alpha版本中可用。

UPDATE: Hooks are now in the public, stable version of React v16.8.

更新:Hooks现在是React v16.8的公共稳定版本 。

Look at the File Editor on the left side of the Sandbox and:

查看沙盒左侧的文件编辑器,然后:

  • Click on ‘Dependencies’

    点击“依赖项”
  • Remove both ‘react’ and ‘react-dom’

    删除“ react”和“ react-dom”
  • Now click on ‘Add Dependency’

    现在点击“添加依赖项”
  • Type ‘react’ in the input box and click on the dropdown by the right of the first result.

    在输入框中输入“React”,然后单击第一个结果右侧的下拉菜单。
  • Select version 16.8.0-alpha.1.

    选择版本16.8.0-alpha.1。
  • Now click on the description to install it.

    现在单击说明进行安装。

Repeat the same steps for ‘react-dom’ and we should be good to go.

对“ react-dom”重复相同的步骤,我们应该一切顺利。

(CODE)

Now that we have the setup out of the way, it’s time to write some code. Hop over to the Sandbox you created, create a new file called Form.jsx and paste the following code in:

现在我们已经完成了设置,现在该写一些代码了。 跳到您创建的沙盒,创建一个名为Form.jsx的新文件,并将以下代码粘贴到其中:

import React, { Component } from "react";
class Form extends Component {  constructor(props) {    super(props);
this.state = {      firstName: "",      lastName: "",      email: "",      password: "",    };
this.handleInputChange = this.handleInputChange.bind(this);  }
handleInputChange(event) {    this.setState({      [event.target.name]: event.target.value    });  }
render() {    const { firstName, lastName, email, password } = this.state;
return (      <form>        <input          value={firstName}          onChange={this.handleInputChange}          placeholder="First name"          type="text"          name="firstName"          required        />        <input          value={lastName}          onChange={this.handleInputChange}          placeholder="Last name"          type="text"          name="lastName"          required        />        <input          value={email}          onChange={this.handleInputChange}          placeholder="Email address"          type="email"          name="email"          required        />        <input          value={password}          onChange={this.handleInputChange}          placeholder="Password"          type="password"          name="password"          required        />
<button type="submit">Submit</button>      </form>    );  }}
export default Form;

Now open index.js and replace the contents with the following code:

现在打开index.js并将内容替换为以下代码:

import React from "react";import ReactDOM from "react-dom";
import Form from "./Form.jsx";import "./styles.css";
function App() {  return (    <div className="App">      <h1>A Simple Form in React</h1>      <Form />    </div>  ); }
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Test the form to see that everything works fine. Now that was the ‘old-school’ way of implementing a controlled form in React.

测试表格,看一切正常。 现在,这是在React中实现受控表单的“老派”方法。

Notice the amount of boilerplate we needed to set up the state and the method for updating it on each input change.

注意,设置状态所需的样板数量以及在每次输入更改时更新状态的方法。

Let’s code the same form using React Hooks (finally!) but first, delete all the code from Form.jsx and let’s start afresh.

让我们使用React Hooks编码相同的表单(最后!),但是首先,从Form.jsx中删除所有代码,然后重新开始。

Start by adding the following line to the top of the file:

首先在文件顶部添加以下行:

import React, { useState } from 'react';

So there’s an unfamiliar method imported here called useState. What is it and how do we use it?

因此,这里导入了一个陌生的方法,称为useState 。 它是什么,我们如何使用它?

Well, useState is the React Hook that will allow us to access and manipulate state in our component. This means we won’t have to extend Component as our previous code does.

好吧, useState是React Hook,它将允许我们访问和操作组件中的state 。 这意味着我们不必像前面的代码那样extend Component

It’s one of several new Hooks coming to the React API to help us write cleaner code. Now let’s use it.

这是React API新增的几个Hook之一,可以帮助我们编写更简洁的代码。 现在让我们使用它。

import React, { useState } from "react";import "./styles.css";
function Form() {  const [firstName, setFirstName] = useState("");  const [lastName, setLastName] = useState("");  const [email, setEmail] = useState("");  const [password, setPassword] = useState("");
return (    <form>      <input        value={firstName}        onChange={e => setFirstName(e.target.value)}        placeholder="First name"        type="text"        name="firstName"        required      />      <input        value={lastName}        onChange={e => setLastName(e.target.value)}        placeholder="Last name"        type="text"        name="lastName"        required      />      <input        value={email}        onChange={e => setEmail(e.target.value)}        placeholder="Email address"        type="email"        name="email"        required      />      <input        value={password}        onChange={e => setPassword(e.target.value)}        placeholder="Password"        type="password"        name="password"        required      />
<button type="submit">Submit</button>    </form>  );}
export default Form;

We’ve created our functional component but there is some unfamiliar code that I will explain. Specifically, the four declarations at the top of our component.

我们已经创建了功能组件,但是我将解释一些不熟悉的代码。 具体来说,这四个声明位于组件顶部。

While that part of the code looks strange at first, it is simple to understand. We are no longer declaring a single object called state that holds our component’s state. Instead, we are now splitting up state into multiple declarations.

虽然这部分代码乍看之下很奇怪,但很容易理解。 我们不再声明一个名为state对象来保存组件的状态。 相反,我们现在将state分成多个声明。

Say we wanted to declare a state variable called firstName the familiar extends React.Component way, we’d usually do it in the constructor and then access it by writing this.state.firstName.

假设我们想以熟悉的extends React.Component方式声明一个名为firstName的状态变量,我们通常在构造函数中进行操作,然后通过编写this.state.firstName进行访问。

But with useState, we initialize two variables called firstName and setFirstName. We then set their values to whatever useState() returns.

但是使用useState ,我们初始化了两个名为firstNamesetFirstName变量。 然后,将其值设置为useState()返回的任何值。

Why do we have to declare setFirstName too though?

为什么我们也必须声明setFirstName

Well, since this is a functional component, we don’t have setState to help us modify the value of the state variable. What we do have is setFirstName whose sole purpose is to update firstName every time we call it.

好吧,由于这是一个功能组件,因此我们没有setState来帮助我们修改状态变量的值。 我们拥有的是setFirstName其唯一目的是每次调用它时都更新firstName

So when you see:

因此,当您看到:

const [firstName, setFirstName] = useState("")

We’re basically declaring a state variable and a function to allow us to modify the state variable later. The empty string in the useState call is the initial value of firstName and can be set to any required value. We’ll set it to an empty string for now.

我们基本上是在声明一个状态变量和一个允许我们稍后修改状态变量的函数。 useState调用中的空字符串是firstName的初始值,可以设置为任何必需的值。 我们现在将其设置为空字符串。

Note that you can name the setFirstName function whatever you want. It is a convention, however, to append ‘set’ before the name of the state variable we’re modifying.

请注意,您可以根据需要命名setFirstName函数。 但是,习惯上要在要修改的状态变量名称前附加“ set”。

We now know how to create a state variable in a functional component and how to update it. Let’s continue by explaining the rest of the code.

现在,我们知道如何在功能组件中创建状态变量以及如何对其进行更新。 让我们继续解释其余的代码。

In our first input tag, we set it’s value to the state variable we declared at the top of our component. As for the onChange handler, we set it to an arrow function that calls the function which updates our state variable for us.

在第一个输入标签中,将其值设置为在组件顶部声明的状态变量。 至于onChange处理程序,我们将其设置为一个箭头函数 ,该函数调用该函数为我们更新状态变量。

Where we had a method in our previous class component called handleInputChange, we now have an anonymous function that updates our state for us.

在先前的类组件中有一个称为handleInputChange的方法中,现在有了一个匿名函数可以为我们更新状态。

Check that everything works as it should by trying to input text into your form. If everything works, congratulations, you just used a React Hook. If not, then go through this tutorial again and ensure you don’t skip any instructions.

尝试在表单中输入文本,以检查一切是否正常。 如果一切正常,那么恭喜,您刚刚使用了React Hook。 如果不是,请再次阅读本教程,并确保您不跳过任何说明。

Add styling as you see fit and enjoy.

根据自己的喜好添加样式,并乐在其中。

反思 (REFLECTIONS)

UPDATE: Some of us may be alarmed at the thought of using inline functions in the onClick handler. I tweeted Dan Abramov about that and he replied with this part of the Hooks documentation that explains why using inline functions with Hooks isn’t a bad thing.

更新:我们中有些人可能会对在onClick处理程序中使用内联函数的想法感到震惊。 我在推特上发布了Dan Abramov的信息,他回答了Hooks文档的这一部分 ,解释了为什么对Hooks使用内联函数不是一件坏事。

Going through our new code and comparing it to the old one, it’s obvious how React Hooks can help us to write better code.

通过阅读我们的新代码并将其与旧代码进行比较,很明显,React Hooks如何帮助我们编写更好的代码。

Comparing the class component and the functional component side by side, it is clear that the functional component is easier to reason about, uses less code, and generally looks cleaner.

并排比较类组件和功能组件,很明显,功能组件更容易推理,使用更少的代码并且通常看起来更简洁。

If you like React Hooks, you can learn more by exploring the official docs and trying to reimplement some of your projects using them.

如果您喜欢React Hooks,可以通过研究官方文档并尝试使用它们重新实现一些项目来了解更多信息。

That said, I’d like to hear your thoughts. Do you think Hooks are the future of React or do you feel that they’re just unnecessary gimmicks? Leave a comment below.

就是说,我想听听您的想法。 您是否认为Hooks是React的未来,还是觉得它们只是不必要的头? 在下面发表评论。

This post appeared first on The Andela Way.

这篇文章首先出现在The Andela Way上 。

翻译自: https://www.freecodecamp.org/news/how-to-get-started-with-react-hooks-controlled-forms-826c99943b92/

react hooks使用

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392101.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

特征工程tf-idf_特征工程-保留和删除的内容

特征工程tf-idfThe next step after exploring the patterns in data is feature engineering. Any operation performed on the features/columns which could help us in making a prediction from the data could be termed as Feature Engineering. This would include the…

c语言定义数组a10 指定各元素,C语言填空题.doc

C语言填空题.doc二、填空题1、C 语言只有 32 个关键字和 9 种控制语句。2、每个源程序有且只有一个 main 函数&#xff0c;系统总是从该函数开始执行 C 语言程序。 3、C 语言程序的注释可以出现在程序中的任何地方&#xff0c;它总是以 * 符号作为开始标记&#xff0c;以 */ 符…

猫狗队列

功能要求&#xff1a; 用户可以调用push方法将cat类或dog类的实例放入队列中;用户可以调用pollAll方法&#xff0c;将队列中所有的实例按照进队列的先后顺序依次弹出;用户可以调用pollDog方法&#xff0c;将队列中dog类的实例按照进队列的先后顺序依次弹出;用户可以调用pollCat…

如何使用HTML5,JavaScript和Bootstrap构建自定义文件上传器

by Prashant Yadav通过Prashant Yadav 如何使用HTML5&#xff0c;JavaScript和Bootstrap构建自定义文件上传器 (How to build a custom file uploader with HTML5, JavaScript, & Bootstrap) In this short article, we’ll learn how to create custom file uploader wit…

monkey测试===通过monkey测试检查app内存泄漏和cpu占用

最近一直在研究monkey测试。网上资料很多&#xff0c;但都是一个抄一个的。原创的很少 我把检查app内存泄漏的情况梳理一下&#xff1a; 参考资料&#xff1a; Monkey测试策略&#xff1a;https://testerhome.com/topics/597 Android Monkey测试详细介绍&#xff1a;http://www…

数据挖掘—主成分分析法降维和最小最大规范化

算法步骤:1)将原始数据按列组成n行m列矩阵X2)特征中心化。即每一维的数据都减去该维的均值&#xff0c;使每一维的均值都为03)求出协方差矩阵4)求出协方差矩阵的特征值及对应的特征向量5)将特征向量按对应的特征值大小从上往下按行排列成矩阵&#xff0c;取前k行组成矩阵p6)YPX…

用户使用说明c语言,(C语言使用指南.docx

(C语言使用指南Turbo C(V2.0)使用指南(本文的许多命令或方法同样适用于TC3) 在开始看本文以前&#xff0c;我先说明一下C语言的安装和使用中最应该注意的地方&#xff1a;许多网友在下载Turbo C 2.0和Turbo C 3.0后&#xff0c;向我问得最多的是在使用过程中碰到如下问题&…

三维空间两直线/线段最短距离、线段计算算法 【转】

https://segmentfault.com/a/1190000006111226d(ls,lt)|sj−tj||s0−t0(be−cd)u⃗ −(ae−bd)v⃗ ac−bd(ls,lt)|sj−tj||s0−t0(be−cd)u⃗ −(ae−bd)v⃗ ac−b2|具体实现代码如下&#xff08;C#实现&#xff09;&#xff1a; public bool IsEqual(double d1, double d2) { …

【慎思堂】之JS牛腩总结

一 JS基础 1-定义 Javascript是一种脚本语言/描述语言&#xff0c;是一种解释性语言。用于开发交互式web网页&#xff0c;使得网页和用户之间实现了一种实时性的、动态的、交互性的关系&#xff0c;使网页包含更多活跃的元素和更加精彩的内容。 主要用于&#xff1a;表单验证 …

vuejs 轮播_如何在VueJS中设计和构建轮播功能

vuejs 轮播by Fabian Hinsenkamp由Fabian Hinsenkamp设计 A carousel, slideshow, or slider — however you call it this class of UI — has become one of the core elements used in modern web development. Today, it’s almost impossible to find any Website or UI …

iOS绘圆形图-CGContextAddArc各参数说明

2019独角兽企业重金招聘Python工程师标准>>> 1.使用 UIGraphicsGetCurrentContext() 画圆 CGContextAddArc(<#CGContextRef _Nullable c#>, <#CGFloat x#>, <#CGFloat y#>, <#CGFloat radius#>, <#CGFloat startAngle#>, <#CGFlo…

c语言中if和goto的用法,C语言中if和goto的用法.doc

C语言中if和goto的用法C语言中&#xff0c;if是一个条件语句&#xff0c;用法??if(条件表达式) 语句如果满足括号里面表达式&#xff0c;表示逻辑为真于是执行后面的语句&#xff0c;否则不执行(表达式为真则此表达式的值不为0&#xff0c;为假则为0&#xff0c;也就是说&…

数据挖掘—K-Means算法(Java实现)

算法描述 &#xff08;1&#xff09;任意选择k个数据对象作为初始聚类中心 &#xff08;2&#xff09;根据簇中对象的平均值&#xff0c;将每个对象赋给最类似的簇 &#xff08;3&#xff09;更新簇的平均值&#xff0c;即计算每个对象簇中对象的平均值 &#xff08;4&#xf…

自我价值感缺失的表现_不同类型的缺失价值观和应对方法

自我价值感缺失的表现Before handling the missing values, we must know what all possible types of it exists in the data science world. Basically there are 3 types to be found everywhere on the web, but in some of the core research papers there is one more ty…

[收藏转载]C# GDI+ 简单绘图(一)

最近对GDI这个东西接触的比较多&#xff0c;也做了些简单的实例&#xff0c;比如绘图板&#xff0c;仿QQ截图等&#xff0e; 废话不多说了&#xff0c;我们先来认识一下这个GDI&#xff0c;看看它到底长什么样. GDI&#xff1a;Graphics Device Interface Plus也就是图形设备接…

mybaties总结+hibernate总结

一、对原生态jdbc程序中问题总结 1.1 jdbc程序 需求&#xff1a;使用jdbc查询mysql数据库中用户表的记录 statement:向数据库中发送一个sql语句 预编译statement&#xff1a;好处&#xff1a;提高数据库性能。 预编译statement向数据库中发送一个sql语句&#xff0c;数据库编译…

客户旅程_我如何充分利用freeCodeCamp的旅程

客户旅程by Catherine Vassant (aka Codingk8)由凯瑟琳瓦森(Catherine Vassant)(又名Codingk8) 我如何充分利用freeCodeCamp的旅程 (How I made the most out of my freeCodeCamp journey) 我的路线图&#xff1f; ️超越课程范围的reeCodeCamp (My road map ?️ to freeCode…

Python14 函数

函数 面向对象编程&#xff1a; 类----class 面向过程编程&#xff1a;过程---def 函数式编程&#xff1a;函数---def def test(x):描述x 1return x#def是定义函数的关键字#test是函数名称#&#xff08;x&#xff09;是参数#x1是 函数体&#xff0c;是一段逻辑代码#return 定义…

学习sql注入:猜测数据库_面向数据科学家SQL:学习简单方法

学习sql注入:猜测数据库We don’t pick a hammer and look for nails — that would be an unusual way of solving problems. The usual way of doing business is to identify the problem first, then look for appropriate tools.我们不用锤子找钉子&#xff0c;那是解决问…

android 百度地图3.0,android 百度地图3.0

一&#xff1a;为地图设置事件注意新版本中要有一个getMapmMapView.getMap().setOnMapStatusChangeListener(listener);OnMapStatusChangeListener listener newOnMapStatusChangeListener() {/*** 手势操作地图&#xff0c;设置地图状态等操作导致地图状态开始改变。* param s…