我正在使用React并具有以下组件:
import React from 'react';
function Calculate({ work }) {
var inputValue = 0;
const totalAmountToBePaid = () => {
inputValue++;
console.log("=====> Total Amount To Be Paid", work);
console.log(inputValue);
};
return (
<div>
<header className="App-header">
<input type="number" id="amount" value={inputValue} readOnly></input>
<button onClick={totalAmountToBePaid}>Total Amount To Be Paid</button>
</header>
</div>
)
}
export default Calculate;
当我单击button
时,我需要它通过调用input
函数来更新totalAmountToBePaid
的值。
上述解决方案只是将input
的值保留为默认值0。
我是React的新手,请原谅我的无知。我想可能需要给一个state
对象。
谢谢
答案 0 :(得分:3)
是的,您缺少状态对象。
将其替换为以下
function Calculate({ work }) {
const [inputValue, setInputValue] = React.useState(0)
const totalAmountToBePaid = () => {
setInputValue(inputValue+1);
console.log("=====> Total Amount To Be Paid", work);
console.log(inputValue);
};
return (
<div>
<header className="App-header">
<input type="number" id="amount" value={inputValue} readOnly></input>
<button onClick={totalAmountToBePaid}>Total Amount To Be Paid</button>
</header>
</div>
)
}
工作示例https://codesandbox.io/s/dank-pine-9hk26
由于您是React的新手,我认为您应该阅读React文档。 https://reactjs.org/docs/state-and-lifecycle.html了解基本知识。
答案 1 :(得分:0)
如果您不需要console.logs,就可以做;
const [inputValue, setInputValue] = useState(0);
<button onClick={() => setInputValue(inputValue+1)}>Total Amount To Be Paid</button>