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(
        <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')
)

 

posted @ 2019-11-10 00:37  sx00xs  阅读(1280)  评论(0编辑  收藏  举报