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 ,我們初始化了兩個名為firstName和setFirstName變量。 然后,將其值設置為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使用