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.pswp.cn/news/392101.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392101.shtml
英文地址,請注明出處:http://en.pswp.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…