Home > Article > Web Front-end > How to implement array summation in react
How to implement array summation in react: 1. Create a code sample file; 2. Enter "import React,{useState,useEffect} from 'react';"; 3. Use controlled components and bind Set the onChange event; 4. Use the "function Sum(){...}" method to implement the sum.
The operating environment of this tutorial: windows10 system, react18 version, DELL G3 computer.
How to implement array summation in react?
React: Find the sum of all the numbers in the array
Requirement: Find the sum of all the numbers in the array
Analysis: Requirement Use controlled components and bind the onChange event (if you don’t bind, React will remind you...)
import React,{useState,useEffect} from 'react'; import ReactDOM from 'react-dom'; import './index.css'; function Sum(){ const [val,setVal]=useState("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15"); const [sum,setSum]=useState(''); const handleVal = function(e) { //let newVal=e.target.value; //newVal=newVal.replace(/[^(\d)|(,)]/,''); setVal(e.target.value.replace(/[^(\d)|(,)]/,'')); //console.log(val); }; const handleClick =function(){ var sum=0; var inputs=val.split(','); for(var i in inputs){ sum += parseInt(inputs[i]); } setSum(sum); } return( <div id="outer"> <label> <input type="text" value={val} onChange={handleVal} /> <span>输入数字求和,数字之间用半角","号分隔</span> </label> <p><button onClick={handleClick}>求和</button></p> <strong className="sum">{sum}</strong> </div> ); } ReactDOM.render( <Sum/>, document.getElementById('root') )
Recommended learning: "react video tutorial"
The above is the detailed content of How to implement array summation in react. For more information, please follow other related articles on the PHP Chinese website!