react前端ui的使用
介绍 (Introduction)
Forms are the standard method used to collect user inputs on web applications. However, sometimes we may be collecting large amounts that may result in a large form with several fields. This can be a pain not just for the user but for the developer as well since they will have to fit these fields into the form in a way that still looks appealing to the user.
表单是用于收集Web应用程序上用户输入的标准方法。 但是,有时我们可能会收集大量的信息,这些信息可能导致具有多个字段的大型表单。 这不仅会给用户带来麻烦,还会给开发人员带来麻烦,因为他们将不得不以仍然吸引用户的方式将这些字段放入表单中。
The solution is to break the form into several sections collecting a certain type of information at each point. React makes this simple to implement. We can do this by breaking down the sections (steps) into individual React components that collect certain inputs. We can then choose which components are rendered at each step by manipulating state. In this tutorial you will see how to do this as well as sharing functionality across components using an example of a registration form.
解决方案是将表格分成几个部分,在每个点上收集某种类型的信息。 React使这一点易于实现。 我们可以通过将各个部分(步骤)分解为收集某些输入的单个React组件来实现。 然后,我们可以通过操作状态来选择在每个步骤中呈现哪些组件。 在本教程中,您将看到一个注册表格示例,以及如何在各个组件之间共享功能以及如何做到这一点。
入门 (Getting Started)
You’ll start the project by using create-react-app which wil take care of configuring the React development environment as well as provide some boilerplate to get us started. To install create-react-app
run the following script in your terminal:
您将使用create-react-app启动项目,该项目将负责配置React开发环境,并提供一些样板来帮助我们开始。 要安装create-react-app
,请在终端中运行以下脚本:
npm install -g create-react-app
Now that we have create-react-app installed. The next step is to initialize our application. To do this run:
现在,我们已经安装了create-react-app。 下一步是初始化我们的应用程序。 要执行此操作:
create-react-app multistep-form
This will create a sample React application with the development environment fully configured. The folder structure will look like this
这将创建一个具有完整配置的开发环境的示例React应用程序。 文件夹结构如下所示
|---public
|------favicon.ico
|------index.html
|------manifest.json
|---src
|------app.css
|------app.js
|------app.test.js
|------index.css
|------index.js #
|------logo.svg
|------registerServiceWorker.js
|---.gitignore
|---package.json
|---README.md
|---yarn.lock
We’ll also be using yarn as our default package manager. Yarn is a great alternative to npm as it locks down dependency versions — a feature that was added to recent versions of npm. Yarn is also the default package manager for create-react-app
. If you don’t have yarn yet, you can find the installation instructions here.
我们还将使用yarn作为默认的程序包管理器。 Yarn是npm的一个很好的选择,因为它可以锁定依赖版本-该功能已添加到npm的最新版本中。 Yarn还是create-react-app
的默认软件包管理器。 如果还没有纱线,可以在此处找到安装说明。
For styling we shall use Semantic UI which is a UI framework easily pluggable into React applications using Semantic UI React. Semantic UI React provides several prebuilt components that we can use to speed up our development process. The framework also supports responsiveness which makes it great for building cross-platform websites. To install it run:
为了进行样式设计,我们将使用语义UI,这是一个易于使用语义UI React插入到React应用程序中的UI框架。 语义UI React提供了几个预构建的组件,我们可以使用它们来加快开发过程。 该框架还支持响应能力,这非常适合构建跨平台的网站。 要安装它,请运行:
yarn add semantic-ui-react
To add the custom semantic UI CSS, add the following to the head
section of the index.html
file.
要添加自定义语义UI CSS,请将以下内容添加到index.html
文件的head
。
// index.html
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.12/semantic.min.css"></link>
Now you’re ready to proceed.
现在您可以继续了。
创建组件 (Creating the Components)
Now that the project is set up let’s create a components
folder under the src
directory in which we’ll place our form components. Inside it it create 5 files: Confirmation.jsx
, MainForm.jsx
, PersonalDetails.jsx
, Success.jsx
, and UserDetails.jsx
. Feel free to define empty class components in each of these files, which we’ll add more functionality to as we work through this tutorial.
现在已经建立了项目,让我们在src
目录下创建一个components
文件夹,在其中放置表单组件。 在其中创建5个文件: Confirmation.jsx
, MainForm.jsx
, PersonalDetails.jsx
, Success.jsx
和UserDetails.jsx
。 可以在每个文件中随意定义空的类组件,在学习本教程时,我们将为其添加更多功能。
Now let’s edit app.js
to import our components and render them. Delete the boilerplate code added by create-react-app
and add the following code instead.
现在,让我们编辑app.js
以导入我们的组件并渲染它们。 删除由create-react-app
添加的样板代码,并添加以下代码。
// app.js
import React, { Component } from 'react';
import './App.css';
import MainForm from './components/MainForm';
import { Container } from 'semantic-ui-react';
class App extends Component {
render() {
return(
<Container textAlign='center'>
<MainForm />
</Container> )
}
}
export default App;
We’ve wrapped the form in a Container
component from Semantic UI React which makes it more presentable by centering the text and adding padding.
我们将表单包装在来自语义UI React的Container
组件中,该组件通过将文本居中并添加填充来使其更具呈现性。
The first component we’ll set up is the MainForm
component which will be in charge of most of the functionality in our application.
我们将设置的第一个组件是MainForm
组件,它将负责我们应用程序中的大多数功能。
// MainForm.jsx
import React, { Component } from 'react';
import UserDetails from './UserDetails';
import PersonalDetails from './PersonalDetails';
import Confirmation from './Confirmation';
import Success from './Success';
class MainForm extends Component {
state = {
step: 1,
firstName: '',
lastName: '',
email: '',
age: '',
city: '',
country: ''
}
nextStep = () => {
const { step } = this.state
this.setState({
step : step + 1
})
}
prevStep = () => {
const { step } = this.state
this.setState({
step : step - 1
})
}
handleChange = input => event => {
this.setState({ [input] : event.target.value })
}
render(){
const {step} = this.state;
const { firstName, lastName, email, age, city, country } = this.state;
const values = { firstName, lastName, email, age, city, country };
switch(step) {
case 1:
return <UserDetails
nextStep={this.nextStep}
handleChange = {this.handleChange}
values={values}
/>
case 2:
return <PersonalDetails
nextStep={this.nextStep}
prevStep={this.prevStep}
handleChange = {this.handleChange}
values={values}
/>
case 3:
return <Confirmation
nextStep={this.nextStep}
prevStep={this.prevStep}
values={values}
/>
case 4:
return <Success />
}
}
}
export default MainForm;
Let’s go through the code we’ve just added. The biggest step we’ve taken towards creating our multistep form is using the switch
statement, which reads the step
from state and uses this to select which components are rendered at each step.
让我们看一下刚刚添加的代码。 我们朝创建多步骤表单迈出的最大一步是使用switch
语句,该语句从状态读取step
,并使用它选择在每个步骤中呈现的组件。
The component is initialized with the default value for step in state as 1
, and the first section of our form is rendered. The user can then skip back and forth between steps using the prevStep
and nextStep
functions. These update the value of step
in state so as to allow the user to switch between the rendered components.
组件将使用步骤1
的默认默认值初始化,并呈现表单的第一部分。 然后,用户可以使用prevStep
和nextStep
函数在步骤之间来回跳过。 这些更新了step
in state的值,以便允许用户在渲染的组件之间切换。
The handleChange
function updates the value of the details provided by the user inside state and like the prevStep
and nextStep
functions, it will be passed to the child components as props. This will allow us to pass the functionality implemented for use within the child components as we are about to see in our next step.
handleChange
函数更新用户内部状态提供的详细信息的值,并且像prevStep
和nextStep
函数一样,它将作为道具传递给子组件。 这将使我们能够传递在子组件中实现的功能,这将在下一步中看到。
Now let’s create the first section of our form. Inside UserDetails.jsx
place the following code.
现在,让我们创建表单的第一部分。 在UserDetails.jsx
放置以下代码。
// UserDetails.jsx
import React, { Component } from 'react';
import { Form, Button } from 'semantic-ui-react';
class UserDetails extends Component{
saveAndContinue = (e) => {
e.preventDefault()
this.props.nextStep()
}
render(){
const { values } = this.props;
return(
<Form >
<h1 className="ui centered">Enter User Details</h1>
<Form.Field>
<label>First Name</label>
<input
placeholder='First Name'
onChange={this.props.handleChange('firstName')}
defaultValue={values.firstName}
/>
</Form.Field>
<Form.Field>
<label>Last Name</label>
<input
placeholder='Last Name'
onChange={this.props.handleChange('lastName')}
defaultValue={values.lastName}
/>
</Form.Field>
<Form.Field>
<label>Email Address</label>
<input
type='email'
placeholder='Email Address'
onChange={this.props.handleChange('email')}
defaultValue={values.email}
/>
</Form.Field>
<Button onClick={this.saveAndContinue}>Save And Continue </Button>
</Form>
)
}
}
export default UserDetails;
This creates a form that collects the user’s first name, last name, and email address. The saveAndContinue
function is then in charge of routing us to the next component once we are done filling the details. You will notice that we have called the nextStep
function which we had provided to the component as props. Each time this function is called, it updates the state of the parent component (MainForm
). We also called handleChange
and provided it the name of each field to be updated on each input element.
这将创建一个表单,该表单收集用户的名字,姓氏和电子邮件地址。 一旦我们完成填充细节,那么saveAndContinue
函数将负责将我们路由到下一个组件。 您会注意到,我们已经调用了作为道具提供给组件的nextStep
函数。 每次调用此函数时,它都会更新父组件( MainForm
)的状态。 我们还调用handleChange
并为其提供每个输入元素上要更新的每个字段的名称。
You may have also noticed that each input field is provided a defaultValue
which it picks from the state of the MainForm
component. This allows it to pick the updated value in state in cases where the user routes back to one step from another as we’ll see in our next component.
您可能还注意到,每个输入字段都提供了一个defaultValue
,它是从MainForm
组件的状态中选取的。 这样,当用户从下一个步骤路由到下一个步骤时,它就可以选择状态更新后的值,这将在下一个组件中看到。
Now let’s create our second section, which collects the user’s personal information. Inside PersonalDetails.jsx
, add the following code.
现在,让我们创建第二部分,该部分收集用户的个人信息。 在PersonalDetails.jsx
,添加以下代码。
// PersonalDetails.jsx
import React, { Component } from 'react';
import { Form, Button } from 'semantic-ui-react';
import { throws } from 'assert';
class PersonalDetails extends Component{
saveAndContinue = (e) => {
e.preventDefault();
this.props.nextStep();
}
back = (e) => {
e.preventDefault();
this.props.prevStep();
}
render(){
const { values } = this.props
return(
<Form color='blue' >
<h1 className="ui centered">Enter Personal Details</h1>
<Form.Field>
<label>Age</label>
<input placeholder='Age'
onChange={this.props.handleChange('age')}
defaultValue={values.age}
/>
</Form.Field>
<Form.Field>
<label>City</label>
<input placeholder='City'
onChange={this.props.handleChange('city')}
defaultValue={values.city}
/>
</Form.Field>
<Form.Field>
<label>Country</label>
<input placeholder='Country'
onChange={this.props.handleChange('country')}
defaultValue={values.country}
/>
</Form.Field>
<Button onClick={this.back}>Back</Button>
<Button onClick={this.saveAndContinue}>Save And Continue </Button>
</Form>
)
}
}
export default PersonalDetails;
This section collects the user’s age and location. The overall functionality is similar to the user details section apart from the addition of the back button which will take us back to the previous step by calling prevStep
from props.
本部分收集用户的年龄和位置。 总体功能类似于用户详细信息部分,除了增加了后退按钮,这将通过从props调用prevStep
将我们带回到上一步。
We have the back
and saveAndContinue
functions in each of our components take an event(e)
as an argument and we call event.preventDefault()
in these functions to stop the form from reloading each time we submit which is the default behavior in forms.
我们每个组件中都有back
和saveAndContinue
函数,将event(e)
作为参数,并在这些函数中调用event.preventDefault()
,以防止每次提交表单时都重新加载表单,这是表单中的默认行为。
Now let’s create the final section of our form where the user confirms the details they have fed the application are correct. Add the following code to Confirmation.jsx
现在,让我们创建表单的最后部分,在该部分中,用户确认输入了应用程序的详细信息正确无误。 将以下代码添加到Confirmation.jsx
// Confirmation.jsx
import React, { Component } from 'react';
import { Button, List } from 'semantic-ui-react';
class Confirmation extends Component{
saveAndContinue = (e) => {
e.preventDefault();
this.props.nextStep();
}
back = (e) => {
e.preventDefault();
this.props.prevStep();
}
render(){
const {values: { firstName, lastName, email, age, city, country }} = this.props;
return(
<div>
<h1 className="ui centered">Confirm your Details</h1>
<p>Click Confirm if the following details have been correctly entered</p>
<List>
<List.Item>
<List.Icon name='users' />
<List.Content>First Name: {firstName}</List.Content>
</List.Item>
<List.Item>
<List.Icon name='users' />
<List.Content>Last Name: {lastName}</List.Content>
</List.Item>
<List.Item>
<List.Icon name='mail' />
<List.Content>
<a href='mailto:jack@semantic-ui.com'>{email}</a>
</List.Content>
</List.Item>
<List.Item>
<List.Icon name='calendar' />
<List.Content>{age} Years</List.Content>
</List.Item>
<List.Item>
<List.Icon name='marker' />
<List.Content>{city}, {country}</List.Content>
</List.Item>
</List>
<Button onClick={this.back}>Back</Button>
<Button onClick={this.saveAndContinue}>Confirm</Button>
</div>
)
}
}
export default Confirmation;
This creates a section that displays all the details entered by the user and asks them to confirm the details before submitting them. This is typically where we would make the final API calls to the backend to submit and save our data. Since this is just a demo, the Confirm
button just implements the same saveAndeContinue
function we used in previous components. However, in a real case scenario we would implement a different submit function that would handle final submission and save the data.
这将创建一个部分,显示用户输入的所有详细信息,并要求他们在提交之前确认这些详细信息。 通常,这是我们对后端进行最终API调用以提交和保存数据的地方。 由于这只是一个演示,因此Confirm
按钮仅实现与先前组件中使用的相同的saveAndeContinue
函数。 但是,在实际情况下,我们将实现另一个提交功能,该功能将处理最终提交并保存数据。
The next and final component in our project is the Success
component which would be rendered when the user successfully saves their information. To create this add the following code to Success.jsx
.
我们项目中的下一个也是最后一个组件是“ Success
组件,当用户成功保存其信息时将呈现该组件。 要创建此代码,请将以下代码添加到Success.jsx
。
// Success.jsx
import React, { Component } from 'react';
class Success extends Component{
render(){
return(
<div>
<h1 className="ui centered">Details Successfully Saved</h1>
</div>
)
}
}
export default Success;
Now fire up your app and walk through the steps.
![UserDetails Section](https://scotch-res.cloudinary.com/image/upload/v1537793704/jpkkiibakzovi3vdqa6o.png)
现在启动您的应用程序并逐步执行步骤。
![用户详细信息部分](https://scotch-res.cloudinary.com/image/upload/v1537793704/jpkkiibakzovi3vdqa6o.png)
结论 (Conclusion)
Multistep forms are great when we need to break down a form into sections. They can also allow us to carry out form validation at each step before carrying on to the next step. The use of a case
statement for routing between steps eliminates the need for a router which means we can easily plug the form into other components without having to adjust routing. It is also possible to set up API calls in between steps if necessary which opens up a number of new possibilities. You can also handle the state better by adding state management tools such as Redux.
当我们需要将表单分解为多个部分时,多步表单非常有用。 它们还可以使我们在继续下一步之前的每个步骤中进行表单验证。 使用case
语句在步骤之间进行路由无需使用路由器,这意味着我们可以轻松地将表单插入其他组件,而无需调整路由。 如有必要,还可以在步骤之间设置API调用,这带来了许多新的可能性。 您还可以通过添加状态管理工具(例如Redux)更好地处理状态。
react前端ui的使用