📜  什么是 useState() 以及它如何用于验证输入值?

📅  最后修改于: 2022-05-13 01:56:49.723000             🧑  作者: Mango

什么是 useState() 以及它如何用于验证输入值?

useState() 是 ReactJs 中的一个钩子,它允许功能组件具有状态。我们在这个函数中传递初始状态,它返回一个变量和一个更新该状态的函数。

  • 我们必须从 react 包中导入 useState() 钩子。

    import  { useState } from 'react';
  • 使用 useState() 钩子创建状态的语法:

    const [ state, updateState] = useState("Initial Value")

useState() 返回一个包含两个元素的列表。第一个是状态本身,第二个是更新这个状态的函数。

创建反应应用程序:

第 1 步:使用以下命令创建一个 React 应用程序:

npx create-react-app foldername

第 2 步:创建项目文件夹(即文件夹名称)后,使用以下命令移动到该文件夹:

cd foldername

项目结构:它将如下所示。

示例 1:
文件名 App.js:

Javascript
import React, { Component, useState } from "react";
const App = () =>   {
    
  const [name, updateName] = useState("kapil")
const handleUpdate = () => {
    
    updateName("Nikhil")
}
    return(
    
             { name }     
    );              } export default App;


Javascript
import React from 'react';
  
export default class App extends React.Component {
      
      state = {
        fields: {},
        errors: {}
    }
    //method to validate values 
    handleValidation = ()=>{
      let fields = this.state.fields;
      let errors = {};
      let formIsValid = true;
  
      //Name check if name is empty or not
      if(!fields["name"]){
         formIsValid = false;
         errors["name"] = "Cannot be empty";
      }
        //name should not contain special char
      if(typeof fields["name"] !== "undefined"){
         if(!fields["name"].match(/^[a-zA-Z]+$/)){
            formIsValid = false;
            errors["name"] = "Only letters";
         }        
      }
   
      //Email should not be empty
      if(!fields["email"]){
         formIsValid = false;
         errors["email"] = "Cannot be empty";
      }
        //validating email
      if(typeof fields["email"] !== "undefined"){
         let lastAtPos = fields["email"].lastIndexOf('@');
         let lastDotPos = fields["email"].lastIndexOf('.');
  
         if (!(lastAtPos < lastDotPos && lastAtPos > 0
         && fields["email"].indexOf('@@') == -1 && 
         lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
            formIsValid = false;
            errors["email"] = "Email is not valid";
          }
     }  
  
     this.setState({errors: errors});
     return formIsValid;
 }
  
    //after submit form it will be called
  handleSubmit = (e) =>{
  e.preventDefault();
    if(this.handleValidation())
      alert("form submitted successfully")
  }
  
    //updating the field value
  handleUpdate(field, e){         
    let fields = this.state.fields;
    fields[field] = e.target.value;        
    this.setState({fields});
}
  
  
   
    render(){
      return (
          
                                                                                     {this.state.errors["name"]}                     
                                                           {this.state.errors["email"]}                     
                                                
    )   } }


输出:

示例 2: React 中输入值的验证允许在用户未使用预期值填写表单时显示错误消息。有很多方法可以使用 React 验证输入值。

文件名 App.js:

Javascript

import React from 'react';
  
export default class App extends React.Component {
      
      state = {
        fields: {},
        errors: {}
    }
    //method to validate values 
    handleValidation = ()=>{
      let fields = this.state.fields;
      let errors = {};
      let formIsValid = true;
  
      //Name check if name is empty or not
      if(!fields["name"]){
         formIsValid = false;
         errors["name"] = "Cannot be empty";
      }
        //name should not contain special char
      if(typeof fields["name"] !== "undefined"){
         if(!fields["name"].match(/^[a-zA-Z]+$/)){
            formIsValid = false;
            errors["name"] = "Only letters";
         }        
      }
   
      //Email should not be empty
      if(!fields["email"]){
         formIsValid = false;
         errors["email"] = "Cannot be empty";
      }
        //validating email
      if(typeof fields["email"] !== "undefined"){
         let lastAtPos = fields["email"].lastIndexOf('@');
         let lastDotPos = fields["email"].lastIndexOf('.');
  
         if (!(lastAtPos < lastDotPos && lastAtPos > 0
         && fields["email"].indexOf('@@') == -1 && 
         lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
            formIsValid = false;
            errors["email"] = "Email is not valid";
          }
     }  
  
     this.setState({errors: errors});
     return formIsValid;
 }
  
    //after submit form it will be called
  handleSubmit = (e) =>{
  e.preventDefault();
    if(this.handleValidation())
      alert("form submitted successfully")
  }
  
    //updating the field value
  handleUpdate(field, e){         
    let fields = this.state.fields;
    fields[field] = e.target.value;        
    this.setState({fields});
}
  
  
   
    render(){
      return (
          
                                                                                     {this.state.errors["name"]}                     
                                                           {this.state.errors["email"]}                     
                                                
    )   } }

输出: