[英]how to sum two inputs with React hooks?
i'm trying to sum two inputs and give a result with a button, i have defined the state hooks and they work but i don't know how to pass the current state to a function and sum it.我正在尝试将两个输入相加并通过按钮给出结果,我已经定义了 state 挂钩并且它们可以工作,但我不知道如何将当前的 state 传递给 ZC1C425268E68385D1AB5074C17A。 Can you please help me?你能帮我么? i'm a beginner here's my code:我是初学者,这是我的代码:
import React from 'react';
export default function Suma (){
//hook defined
const [input, setInput] = React.useState({
num1: "",
num2: "",
});
//handle input change
const handleInput = function(e){
setInput({
...input,
[e.target.name]: e.target.value
});
};
//suma function
const suma = function(){
}
return (
<div>
<input onChange={handleInput} name="num1" value={input.num1} type="text"></input>
<input onChange={handleInput} name="num2" value={input.num2} type="text"></input>
<button>+</button>
<span>resultado</span>
</div>
)
};
If you only want to show the result on click, I think this should be enough如果您只想在点击时显示结果,我认为这应该足够了
export default function Suma (){
//hook defined
const [input, setInput] = React.useState({
num1: "",
num2: "",
});
const [result, setResult] = React.useState("")
//handle input change
const handleInput = function(e){
setInput({
...input,
[e.target.name]: e.target.value
});
};
//suma function
const suma = function(){
const { num1, num2 } = input;
setResult(Number(num1) + Number(num2));
}
return (
<div>
<input onChange={handleInput} name="num1" value={input.num1} type="text"></input>
<input onChange={handleInput} name="num2" value={input.num2} type="text"></input>
<button onclick={suma}>+</button>
<span>resultado: {result}</span>
</div>
)
};
import React from 'react'; export default function Suma (){ //hook defined const [input, setInput] = React.useState({ num1: "", num2: "", }); const [sum, setSum] = React.useState(undefined) useEffect(() => { setSum(parseInt(input.num1) + parseInt(input.num2)) }, [input]) //handle input change const handleInput = function(e){ setInput({ ...input, [e.target.name]: e.target.value }); }; return ( <div> <input onChange={handleInput} name="num1" value={input.num1} type="text"></input> <input onChange={handleInput} name="num2" value={input.num2} type="text"></input> <button>+</button> {sum !== undefined && <span>{sum}</span>} </div> ) };
function AddForm() {
const [sum, setSum] = useState(0);
const [num, setNum] = useState(0);
function handleChange(e) {
setNum(e.target.value);
}
function handleSubmit(e) {
setSum(sum + Number(num));
e.preventDefault();
}
return <form onSubmit={handleSubmit}>
<input type="number" value={num} onChange={handleChange} />
<input type="submit" value="Add" />
<p> Sum is {sum} </p>
</form>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.