首页 > 其他分享 >How to use handleChange() function in react component?

How to use handleChange() function in react component?

时间:2023-07-03 16:56:31浏览次数:39  
标签:function use component value following input handleChange event

An onChange event is triggered when values are entered in the input. This fires a function handleChange(), that is used to set a new state for the input.

1. Handling Single Input

First, we have to set up the input field as a controlled component so that we have a controlled component that senses changes and updates the state accordingly.

 

We will learn handleChange() function with the help of a project in which we’re going to use handleChange() function to display the entered input.

Creating React Application:

   

Step 1: Create a React application using the following command:

npx create-react-app handlechangedemo

Step 2: After creating your project folder i.e. handlechangedemo, move to it using the following command:

cd handlechangedemo

Project Structure: It will look like the following.

 

Project Structure

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

  • Javascript
 
import React, { useState } from "react";   const App = () => {   /*  Initial State */   let [Name, setname] = useState('');     /* The handleChange() function to set a new state for input */   const handleChange = (event) => {     setname(event.target.value);   }     return (     /* Short-form of React.Fragement*/     <>       <form>         { /* The handleChange() is triggered when text is entered */}         <div>           <h1>My Name is <span style={{ color: 'red' }} >             {Name}</span></h1>           <input             type="text"             value={Name}             onChange={handleChange}             placeholder="Enter a text"           />         </div>       </form>     </>   ) }   export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

The following will be the output if the user enters an input which is set with the help of handleChange() function as shown below:

2. Handling Multiple Input

In the above project write down the following code in the App.js file for handling multiple inputs.

  • Javascript
 
import React, { useState } from 'react';   const App = () => {   let [Fullname, setFullname] = useState({     fname: '',     lname: ''   })     const handleChange = (event) => {     let value = event.target.value;     let name = event.target.name;       setFullname((prevalue) => {       return {         ...prevalue,   // Spread Operator                       [name]: value       }     })   }     return (     <>       <form>         <div>           <h1>Hello <span style={{ color: 'red' }}>{Fullname.fname}</span>             <span style={{ color: 'green' }}>{Fullname.lname}</span></h1>           <input type='text' placeholder='Enter Your FirstName'             onChange={handleChange} name='fname' />           <input type='text' placeholder='Enter Your LastName'             onChange={handleChange} name='lname' />         </div>       </form>     </>   ) }   export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

The following will be the output if the user enters an input which is set with the help of handleChange() function as shown below: 

Explanation: We have added name property in case of multiple inputs so that we can identify which input field fired the handleChange() function. We have used the spread operator because when the handleChange() function has been fired, we need the current value of fname and lname (because only then we can add(or assign) the entered input to the state variables(fname and lname)) which are stored in the state object, so we used spread operator to take an existing state object.

How this [name]: value statement works?

This statement assigns the value to that input field whose name (Property) matches the value.

Alternatives to the handleChange function 

There are several alternatives to the handleChange function you provided here are a few of them :

Using an anonymous function:

  • HTML
 
<input type="text" onChange={(event) => setname(event.target.value)} />

Using a named function:

  • Javascript
 
function handleInputChange(event) {   setname(event.target.value); }   <input type="text" onChange={handleInputChange} />

Using the bind method:

  • HTML
 
<input type="text" onChange={setname.bind(null, event.target.value)} />  

标签:function,use,component,value,following,input,handleChange,event
From: https://www.cnblogs.com/weifeng1463/p/17523282.html

相关文章

  • spring报错-Caused by: java.lang.IllegalArgumentException: Unsupported class file
    这个错误原因是因为JDK版本过高,改一下版本就行了把里面的19改成8这样就行了......
  • 基于 Spring Cloud Function 的 Azure Function 开发
    Notice:本文章不包含AzureFunction环境配置等内容1.1前提Azure账户,且有可使用的订阅Azure支持的JDK(本教程适用于JDK1.8)IntelliJIDEA社区版或无限制版均可Maven3.5+最新的FunctionCoreTools1.2创建SpringCloudFunctionAzure工程在Github仓......
  • 1418 - This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in
    项目场景:mysql创建function报错误1418-ThisfunctionhasnoneofDETERMINISTIC,NOSQL,orREADSSQLDATAin问题描述:执行创建函数的sql语句时,提示:ThisfunctionhasnoneofDETERMINISTIC,NOSQL,orREADSSQLDATAinitsdeclarationandbinaryloggingisenab......
  • react-native项目启动报错 Error: `fsevents` unavailable (this watcher can only be
    react-native项目启动报错——watchman安装问题(macpro) LookingforJSfilesin/Users/你的名称/Documents/project/文件夹名Loadingdependencygraph.../Users/你的名称/Documents/project/文件夹名/node_modules/metro/node_modules/sane/src/fsevents_watcher.js:37......
  • 2023-07-03 uniapp小程序端报错:TypeError: eval is not a function
    完整报错:ErrorinonLoadhook:"TypeError:evalisnotafunction" onLoad钩子中的错误:“TypeError:eval不是函数”原因:代码里使用了eval函数,小程序端不支持该函数,h5端和app(Android)端支持。解决方案:小程序端采取替换eval方案。注意:eval函数被认为是不安全的函数,存在脚本代......
  • Angular Component 里 get 关键字修饰的属性的用法
    在Angular中,get关键字用于定义一个访问器属性(accessorproperty),它是一种特殊的属性,可以通过在类中定义一个带有get关键字的方法来实现。当访问这个属性时,会调用这个get方法,并返回该方法的返回值。这种方法使得访问属性时可以执行一些自定义操作,例如计算属性值、验证数据或......
  • Angular Component 里使用 const 和 readonly 修饰的属性有什么区别
    在Angular组件中,我们可以使用const和readonly关键字来修饰成员属性。这两个关键字的目的都是为了确保数据的不变性,但它们在实现和用法上有很大的区别。在本文中,我们将详细讨论这两者之间的区别,并在不少于2800字的篇幅内进行深入分析。首先,让我们了解一下const和readon......
  • IOS开发-NSUserDefaults的基本使用,缓存数据实现数据持久化
    NSUserDefaults是iOS与macOS中的一个存储对象。它用于存储应用程序运行期间和退出后需要保存的数据。NSUserDefaults的特点:-基于键值对:使用字符串作为键名存储数据。-支持的类型:NSString、NSNumber、NSDate、NSArray、NSDictionary等基本数据结构。-存储在本地:数据存储......
  • appassembler-maven-plugin useAllDependencies
    http://mojo.codehaus.org/appassembler/appassembler-maven-plugin/assemble-mojo.htmlThefollowingcanbeusedtouseallprojectdependenciesinsteadofthedefaultbehaviorwhichrepresentsruntimedependenciesonly.forgoal:assembleitcanaddothersc......
  • React - 14 Hooks组件之useRef
    1.获取元素的3种方式方式1:ref={x=>refName=x}函数组件中没有this,直接给了一个变量。(可以用但是不推荐)方式2React.createRef()方式3useRef(null)2.函数组件用useRef,类组件用React.createRefimportReact,{useState,useEffect,useRef}from"react";import{Butto......