react 使用hooks_用react hooks和php建立联系表格

react 使用hooks

重点 (Top highlight)

A while ago I wrote an article about creating a contact form using React and PHP. Many people found it interesting. So, here I am writing an updated version of that article.

不久前,我写了一篇有关使用React和PHP创建联系表单的文章。 许多人发现它很有趣。 所以,我在这里写那篇文章的更新版本。

Check out the article about creating a contact form with React and PHP:

查看有关使用React和PHP创建联系表单的文章:

Hooks are a new addition in React and we are going to re-create the contact form using React Hooks.

挂钩是React中的新增功能,我们将使用React挂钩重新创建联系表单。

先决条件? 并不是的! (Prerequisites? Not really!)

Same as the previous project. This tutorial is beginners friendly. You don’t have to be an expert in Javascript, React, or PHP but I won’t go into basic details like installing React and setting up the project.

与上一个项目相同 本教程对初学者友好。 您不必是Javascript,React或PHP的专家,但我不会介绍诸如安装React和设置项目之类的基本细节。

I assume you already have an up and running React project. We will focus on creating the component.

我假设您已经有一个正在运行的React项目。 我们将专注于创建组件。

创建组件 (Creating the component)

If you have a component folder in your project please go ahead and create a ‘Form’ folder inside it. It is up to you to decide where the component should live. Once you created the folder let’s create the ‘index.js’ file.

如果您的项目中有一个组件文件夹,请继续在其中创建一个“ Form”文件夹。 由您决定组件应该放置在哪里。 创建文件夹后,让我们创建“ index.js”文件。

If you have seen the previous article, we created a class component but this time we don’t need it. Instead, we need to create a function like this:

如果您看过上一篇文章,我们创建了一个类组件,但是这次我们不需要它。 相反,我们需要创建一个像这样的函数:

const Form = (props) => {


}


export default Form;

In order to use React Hooks, we will have to import useState from React. On the top of your file now you can import useState and all the other necessary packages/files.

为了使用React Hooks,我们将不得不从React导入useState。 现在,您可以在文件顶部导入useState和所有其他必要的包/文件。

import React, {useState} from "react";
import PropTypes from "prop-types";
import axios from "axios";
import "./styles.css";


const Form = (props) => {


}


export default Form;

As you can see we will use the package ‘axios’ to fetch data. If you don’t have this package in your project, please install it using Npm or Yarn:

如您所见,我们将使用包“ axios”来获取数据。 如果您的项目中没有此软件包,请使用Npm或Yarn安装它:

npm install axios

(State)

We will use useState to store data on the local state. For example, We will store form data in one state, and errors and success messages will store in separate states. With these states your function will look like this:

我们将使用useState在本地状态上存储数据。 例如,我们将表单数据存储在一种状态,错误和成功消息将存储在不同的状态。 在这些状态下,您的函数将如下所示:

import React, {useState} from "react";
import PropTypes from "prop-types";
import axios from "axios";
import "./styles.css";


const Form = (props) => {
  const [mailSent, setmailSent] = useState(false);
  const [error, setError] = useState(null);
  const [formData, setFormData] = useState({});
  
  
}


export default Form;


Form.propTypes = {
  config: PropTypes.object.isRequired
};

Additionally, we will have a prop called ‘config’ to get the form title and other configurations for the form.

另外,我们将有一个名为“ config”的道具来获取表单标题和表单的其他配置。

视图 (View)

Essentially I used the code from my previous article but the design has been improved.

本质上,我使用了上一篇文章中的代码,但是 设计 已经改善。

Image for post

The title and description are coming from the ‘config’ prop. In order to create flexible fields, we need to pass a prop called ‘fieldsConfig’

标题和描述来自“ config”道具。 为了创建灵活的字段,我们需要传递一个名为“ fieldsConfig”的道具

This is an object with some properties. For example:

这是具有某些属性的对象。 例如:

id: 1, label: ‘First Name’,fieldName: ‘firstName’,type: ‘text’,placeholder:’Your First Name’, isRequired: true, className:’first-name-field’

id:1,标签:'名字',fieldName:'名字',类型:'文本',占位符:'您的名字',isRequired:true,className:'名字字段'

Your function will look like this within the form:

您的函数在表单中将如下所示:

import React, {useState} from "react";
import PropTypes from "prop-types";
import axios from "axios";
import "./styles.css";


const Form = (props) => {
  const [mailSent, setmailSent] = useState(false);
  const [error, setError] = useState(null);
  const [formData, setFormData] = useState({});
  
  const { title,description, successMessage, errorMessage, fieldsConfig } = props.config;
  
    return (
      <div className="contact-form">
        <div className="contact-form__header">
            <h2>{title}</h2>
            <p>{description}</p>
        </div>
      <div className="contact-form__container">
        <div>
          <form action="#">
            {fieldsConfig &&
              fieldsConfig.map(field => {
                return (
                  <React.Fragment key={field.id}>
                    {field.type !== "textarea" ? (
                      <React.Fragment>
                        <label>{field.label}</label>
                        <input
                          type={field.type}
                          className={field.klassName}
                          placeholder={field.placeholder}
                          value={field.name}
                          onChange={e => handleChange(e, field.fieldName)}
                        />
                      </React.Fragment>
                    ) : (
                      <React.Fragment>
                        <label>{field.label}</label>
                        <textarea className={field.klassName} placeholder={field.placeholder} onChange={e => handleChange(e, field.fieldName)} value={field.name} />
                      </React.Fragment>
                    )}
                  </React.Fragment>
                );
              })}
            <input type="submit" onClick={e => handleFormSubmit(e)} value="Submit" />
            <div>
              {mailSent && <div className="sucsess">{successMessage}</div>}
              {error && <div className="error">{errorMessage}</div>}
            </div>
          </form>
        </div>
        </div>
      </div>
    );
  
}


export default Form;


Form.propTypes = {
  config: PropTypes.object.isRequired
};

大事记 (Events)

We have two important events in this form. One is to handle the form submit and the other is to handle the form change.

这种形式有两个重要事件。 一种是处理表单提交,另一种是处理表单更改。

Let’s create a function to handle the submit event. We will call the function: ‘handleFormSubmit’. The function will look like this.

让我们创建一个函数来处理Submit事件。 我们将调用函数:“ handleFormSubmit”。 该函数将如下所示。

/**
  * @function handleFormSubmit
  * @param e { obj } - form event
  * @return void
  */
  const handleFormSubmit = e => {
    e.preventDefault();
    axios({
      method: "post",
      url: `${process.env.REACT_APP_API}`,
      headers: { "content-type": "application/json" },
      data: formData
    })
      .then(result => {
        if (result.data.sent) {
          setmailSent(result.data.sent)
          setError(false)
        } else {
          setError(true)
        }
      })
      .catch(error => setError( error.message ));
  };

Fundamentally, this function is responsible for sending data to the PHP API. I will explain more about the API soon. When we are getting a successful response from the API we are setting mailSent state with the response and the error state to false. In case we get an error from the response we will update the error state with the response.

从根本上讲,此函数负责将数据发送到PHP API。 我将在不久的将来进一步解释该API。 当我们从API获得成功的响应时,我们会将响应设置为mailSent状态,并将错误状态设置为false。 如果我们从响应中得到一个错误,我们将使用响应来更新错误状态。

If you need a better explanation about this function please check out my previous article:

如果您需要有关此功能的更好说明,请查看我以前的文章:

We are going to need another function to handle any change of input fields. The handleChange will trigger and update formData state whenever the user types something in the text fields.

我们将需要另一个函数来处理输入字段的任何更改。 每当用户在文本字段中键入内容时,handleChange将触发并更新formData状态。

the handleChange function will look like this:

handleChange函数将如下所示:

/**
    * @function handleChange
    * @param e { obj } - change event
    * @param field { string } - namve of the field
    * @return void
    */
   const handleChange = (e, field) => {
    let value = e.target.value;
    setFormData({
      ...formData,
      [field]: value,
    });
  };

Finally, this is the full overview of the Form Component:

最后,这是表单组件的完整概述:

import React, {useState} from "react";
import PropTypes from "prop-types";
import axios from "axios";
import "./styles.css";


/**
 * @component Form
 * @props - { object } -  config
 */
const Form = (props) => {
  const [mailSent, setmailSent] = useState(false);
  const [error, setError] = useState(null);
  const [formData, setFormData] = useState({});
 
  /**
  * @function handleFormSubmit
  * @param e { obj } - form event
  * @return void
  */
  const handleFormSubmit = e => {
    e.preventDefault();
    axios({
      method: "post",
      url: `${process.env.REACT_APP_API}`,
      headers: { "content-type": "application/json" },
      data: formData
    })
      .then(result => {
        if (result.data.sent) {
          setmailSent(result.data.sent)
          setError(false)
        } else {
          setError(true)
        }
      })
      .catch(error => setError( error.message ));
  };
  /**
    * @function handleChange
    * @param e { obj } - change event
    * @param field { string } - namve of the field
    * @return void
    */
   const handleChange = (e, field) => {
    let value = e.target.value;
    setFormData({
      ...formData,
      [field]: value,
    });
  };


    const { title,description, successMessage, errorMessage, fieldsConfig } = props.config;
    return (
      <div className="contact-form">
        <div className="contact-form__header">
            <h2>{title}</h2>
            <p>{description}</p>
        </div>
      <div className="contact-form__container">
        <div>
          <form action="#">
            {fieldsConfig &&
              fieldsConfig.map(field => {
                return (
                  <React.Fragment key={field.id}>
                    {field.type !== "textarea" ? (
                      <React.Fragment>
                        <label>{field.label}</label>
                        <input
                          type={field.type}
                          className={field.klassName}
                          placeholder={field.placeholder}
                          value={field.name}
                          onChange={e => handleChange(e, field.fieldName)}
                        />
                      </React.Fragment>
                    ) : (
                      <React.Fragment>
                        <label>{field.label}</label>
                        <textarea className={field.klassName} placeholder={field.placeholder} onChange={e => handleChange(e, field.fieldName)} value={field.name} />
                      </React.Fragment>
                    )}
                  </React.Fragment>
                );
              })}
            <input type="submit" onClick={e => handleFormSubmit(e)} value="Submit" />
            <div>
              {mailSent && <div className="sucsess">{successMessage}</div>}
              {error && <div className="error">{errorMessage}</div>}
            </div>
          </form>
        </div>
        </div>
      </div>
    );
}


export default Form;
//propTypes for the component
Form.propTypes = {
  config: PropTypes.object.isRequired
};

I have created a GitHub repo to make it easier to follow. Feel free to clone it and play around with it:

我创建了一个GitHub存储库,以使其更容易理解。 随意克隆并尝试一下:

I have a better explanation about the PHP part in my previous article. You can also follow this folder from the GitHub repo to set it up.

上一篇文章中对PHP部分有更好的解释 您还可以从GitHub存储库中跟踪此文件夹进行设置。

If you still missed anything from these articles, I have also published a video here:

如果您仍然错过这些文章中的任何内容,我也在这里发布了一个视频:

Thanks for reading! I hope this article helped you to understand the way ReactHooks works practically.

谢谢阅读! 我希望本文能帮助您了解ReactHooks的实际工作方式。

Cheers!

干杯!

翻译自: https://medium.com/@malith.dev/build-a-contact-form-with-react-hooks-and-php-47bc27927e54

react 使用hooks

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值