react受控组件
Are you currently remaking your class components into stateless functional components but don’t know how to do the same with your controlled forms ? You’ve come to the right place! In this blog post I will be giving a brief introduction to react hooks and how you can build controlled forms without using state. Let’s get started.
您当前是否正在将类组件重新构造为无状态功能组件,但不知道如何对您的受控表单执行相同的操作? 您来对地方了! 在这篇博客文章中,我将简要介绍一下react hooks,以及如何在不使用状态的情况下构建受控表单。 让我们开始吧。
什么是挂钩? (What are Hooks ?)
According to the React docs:
根据React文档:
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
挂钩是React 16.8中的新增功能。 它们使您无需编写类即可使用状态和其他React功能。
In a few words, hooks are a simpler, more concise way to write components. In order to create a functional component that uses hooks, we will need to use a react function called useState( ). This function allows us to create a variable that will save the state, as well as a function whose only job is to update the state. See below for an example:
简而言之,钩子是编写组件的一种更简单,更简洁的方法。 为了创建使用钩子的功能组件,我们将需要使用一个名为useState()的react函数。 这个函数允许我们创建一个保存状态的变量,以及一个唯一的工作就是更新状态的函数。 参见以下示例:
import React, { useState } from 'react'
export default function CounterApp() {
const [count, setCount] = useState(0);
// variable count mimics this.state.count
// function setCount mimics this.setState({ count: newCount })
return <p>{ count }</p>
}
In the example above we created a CounterApp class component that initializes a variable called count to zero and a function called setCount which is responsible for updating the count variable. If we had a class component we would have to initialize that variable within the state of the component and use setState to update it. As you can see, using hooks allows us to achieve the same objective with fewer lines of code.
在上面的示例中,我们创建了一个CounterApp类组件,该组件将名为count的变量初始化为零,并将名为setCount的函数初始化为负责更新count变量的函数。 如果我们有一个类组件,则必须在组件状态内初始化该变量,然后使用setState对其进行更新。 如您所见,使用钩子可以使我们用更少的代码行实现相同的目标。
Now that we got the basics out of the way let’s transform a controlled form built using a class component into a functional stateless component using hooks!
现在我们已经掌握了基础知识,让我们使用钩子将使用类组件构建的受控形式转换为功能性无状态组件!
Let’s start with a class component called SimpleForm with three inputs: name, last name and email address. As you can see below, we have a method called handleChange() that is updating the state every time there is a change within each input.
让我们从一个名为SimpleForm的类组件开始,它具有三个输入:名称,姓氏和电子邮件地址。 如您在下面看到的,我们有一个名为handleChange()的方法,该方法在每次输入中每次发生更改时都会更新状态。
import React, { Component } from "react";
class SimpleForm extends Component {
state = {
name: "",
lastname: "",
email: "",
};
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
};
render() {
return (
<form>
<label htmlFor="name">
Name
<input
type="text"
name="name"
value={this.state.name}
onChange={this.handleChange}
/>
</label>
<label htmlFor="name">
Lastname
<input
type="text"
name="lastname"
value={this.state.lastname}
onChange={this.handleChange}
/>
</label>
<label htmlFor="name">
Email
<input
type="text"
name="email"
value={this.state.email}
onChange={this.handleChange}
/>
</label>
</form>
);
}
}
export default SimpleForm;
Transforming a class components into functional stateless component is a matter of following a couple steps. First, let’s replace the current state with hooks.
将类组件转换为功能性无状态组件仅需遵循几个步骤即可。 首先,让我们用钩子替换当前状态。
import React, { Component, useState } from "react";
class SimpleForm extends Component {
const [name, setName] = useState("");
const [lastname, setLastname] = useState("");
const [email, setEmail] = useState("");
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
};
render() {
return (
<form>
<label htmlFor="name">
Name
<input
type="text"
name="name"
value={this.state.name}
onChange={this.handleChange}
/>
</label>
<label htmlFor="name">
Lastname
<input
type="text"
name="lastname"
value={this.state.lastname}
onChange={this.handleChange}
/>
</label>
<label htmlFor="name">
Email
<input
type="text"
name="email"
value={this.state.email}
onChange={this.handleChange}
/>
</label>
</form>
);
}
}
export default SimpleForm;
Great! Now that that’s out of the way, let’s get rid of all “this” and “this.state” statements.
大! 既然这已经成为问题,让我们摆脱所有“ this”和“ this.state”语句。
import React, { Component, useState } from "react";
class SimpleForm extends Component {
const [name, setName] = useState("");
const [lastname, setLastname] = useState("");
const [email, setEmail] = useState("");
handleChange = (event) => {
setState({ [event.target.name]: event.target.value });
};
render() {
return (
<form>
<label htmlFor="name">
Name
<input
type="text"
name="name"
value={name}
onChange={handleChange}
/>
</label>
<label htmlFor="name">
Lastname
<input
type="text"
name="lastname"
value={lastname}
onChange={handleChange}
/>
</label>
<label htmlFor="name">
Email
<input
type="text"
name="email"
value={email}
onChange={handleChange}
/>
</label>
</form>
);
}
}
export default SimpleForm;
Next, we will get rid of the handleChange function since it doesn’t make sense to keep it here anymore. Instead we will use the new functions we created to update our variables.
接下来,我们将摆脱handleChange函数,因为不再将其保留在这里了。 相反,我们将使用创建的新函数来更新变量。
import React, { Component, useState } from "react";
class SimpleForm extends Component {
const [name, setName] = useState("");
const [lastname, setLastname] = useState("");
const [email, setEmail] = useState("");
render() {
return (
<form>
<label htmlFor="name">
Name
<input
type="text"
name="name"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</label>
<label htmlFor="name">
Lastname
<input
type="text"
name="lastname"
value={lastname}
onChange={(event) => setLastname(event.target.value)}
/>
</label>
<label htmlFor="name">
Email
<input
type="text"
name="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
</label>
</form>
);
}
}
export default SimpleForm;
Almost there. Lastly, we will convert the class component into a functional component by getting rid of the render method and the “class” and “extends Component” keyword.
差不多好了。 最后,我们将通过放弃render方法以及“ class”和“ extends Component”关键字将类组件转换为功能组件。
import React, { useState } from "react";
export default function SimpleForm() {
const [name, setName] = useState("");
const [lastname, setLastname] = useState("");
const [email, setEmail] = useState("");
return (
<form>
<label htmlFor="name">
Name
<input
type="text"
name="name"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</label>
<label htmlFor="name">
Lastname
<input
type="text"
name="lastname"
value={lastname}
onChange={(event) => setLastname(event.target.value)}
/>
</label>
<label htmlFor="name">
Email
<input
type="text"
name="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
</label>
</form>
);
}
Congratulations! You just built your first controlled form using a stateless functional component and hooks. I hope this helped and happy coding!
恭喜你! 您刚刚使用无状态功能组件和挂钩构建了第一个受控表单。 希望这对您有所帮助,并祝您编程愉快!
翻译自: https://medium.com/@emilioquintana90/building-a-controlled-form-using-react-hooks-30c77c35138c
react受控组件