我正在使用 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;
当我单击按钮
时,我需要它通过调用totalAmountToBePaid
函数来更新输入
的值。
上述解决方案只是将输入
的值保留为默认值0。
我是 React 新手,所以请原谅我的无知。我想我可能需要提供一个 state
对象。
谢谢
最佳答案
是的,您缺少状态对象。
将其替换为以下内容
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了解基础知识。
关于javascript - React - 无法设置输入框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58519500/