React练习 9 :求出数组中所有数字的和

需求:求出数组中所有数字的和

解析:需使用受控组件,并绑定onChange事件(不绑定,React会提醒你。。。)

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(
        

{sum}
); } ReactDOM.render( , document.getElementById('root') )

 

你可能感兴趣的:(React练习 9 :求出数组中所有数字的和)