React Exercise 9: Find an array of all the numbers and

Requirements: find an array of all the numbers and

Analysis: need to use the controlled components, and bind onChange event (not binding, 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}
                />
                A half angle between the <span> input digital sum, the number "," separated by </ span>
            </label>
            <p><button onClick={handleClick}>求和</button></p>
            <strong className="sum">{sum}</strong>
        </div>
    );
}

ReactDOM.render(
    <Sum/>,
    document.getElementById('root')
)

 

Guess you like

Origin www.cnblogs.com/sx00xs/p/11828675.html