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使用