react前端ui的使用_如何使用React和Semantic UI创建多步骤表单

news/2024/7/5 20:20:44

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.jsxMainForm.jsxPersonalDetails.jsxSuccess.jsxUserDetails.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的默认默认值初始化,并呈现表单的第一部分。 然后,用户可以使用prevStepnextStep函数在步骤之间来回跳过。 这些更新了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函数更新用户内部状态提供的详细信息的值,并且像prevStepnextStep函数一样,它将作为道具传递给子组件。 这将使我们能够传递在子组件中实现的功能,这将在下一步中看到。

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.

我们每个组件中都有backsaveAndContinue函数,将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

现在启动您的应用程序并逐步执行步骤。

用户详细信息部分

结论 (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)更好地处理状态。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-create-multistep-forms-with-react-and-semantic-ui

react前端ui的使用


http://www.niftyadmin.cn/n/3649634.html

相关文章

Android项目实战系列—基于博学谷(五)个人资料

由于这个模块内容较多,篇幅较长&#xff0c;请耐心阅读。 个人资料模块分为两个部分 个人资料 资料修改 一、个人资料 1、个人资料界面 &#xff08;1&#xff09;、创建个人资料界面 在com.buxuegu.activity包中创建一个java类&#xff0c;命名为UserInfoActivity。在res/l…

[J2ME]VideoCoolala(MobileWebCam)开源说明

不知道80/20原理最初的说法是怎样的&#xff0c;后来有了很多变种。说一种比较通用的吧&#xff0c;你care 100的东西&#xff0c;可以产生100的结果&#xff0c;但这100结果中&#xff0c;有80是你所care的100中的20带来的&#xff1b;剩下20是其余80带来的。于是就有人说了&a…

node.js启动应用命令_如何使用Node.js构建命令行应用程序

node.js启动应用命令As a developer, chances are you spend most of your time in your terminal, typing in commands to help you get around some tasks. 作为开发人员&#xff0c;您很可能会花费大部分时间在终端上&#xff0c;输入命​​令来帮助您解决一些任务。 Some …

[p2p]手机是否可以通过JXTA网络与PC机/PocketPC/WindowsMobile实现P2P呢?

本文只是探讨一下这种可能性。粗粗地看了JXTA&#xff0c;他的目标很宏大&#xff0c;不局限于各种设备&#xff0c;不局限于各种平台&#xff0c;只要能够保持心跳&#xff0c;就算是P2P的一个对等实体。下载并运行了myJXTA&#xff0c;还可以。又看了JXTA的J2ME实现&#xff…

Android项目实战系列—基于博学谷(六)习题模块

由于这个模块内容较多,篇幅较长&#xff0c;请耐心阅读。 习题模块分为两个部分 习题列表界面 习题详情界面 一、习题列表界面 1、习题界面 &#xff08;1&#xff09;、创建习题界面 在res/layout文件夹中&#xff0c;新建一个布局文件&#xff0c;命名为main_view_exercis…