reactjs - 动态计算输入值 - React
问题描述
我正在处理一个由用户填写的表单,并且应该根据输入的数据同时更新其他输入字段。例如,如果我们有 3 个输入字段,数字 1、数字 2 及其总和。我们如何根据用户类型更新它们中的每一个?我当前实现的问题是它并不总是有效。如果一个字段 id 自动呈现并且我尝试手动更改它,那么一切都会停止。换句话说,应用程序没有考虑从公式计算的值,它们只是在字段中呈现。
import React, { useState } from 'react';
const Calculations = () => {
const [values,setValues]=useState({first:"",second:"",sum:""})
const [first,setFirst]=useState('')
const [second,setSecond]=useState('')
const [sum,setSum]=useState('')
const onChange=(e)=>{
let name=e.target.name;
let value=e.target.value;
const newValues = {
...values,
[name]: value
}
setValues(newValues)
calcSum(newValues)
calcfirst(newValues)
calcSecond(newValues)
}
const calcSum = (newValues) => {
const { first,second} = newValues;
const newSum = parseInt(first,10)+parseInt(second,10)
setSum(newSum)
}
const calcfirst = (newValues) => {
const { sum,second} = newValues;
const newFirst = parseInt(sum,10)-parseInt(second,10)
setFirst(newFirst)
}
const calcSecond = (newValues) => {
const { sum,first} = newValues;
const newSecond = parseInt(sum,10)-parseInt(first,10)
setSecond(newSecond)
}
return ( <form>
<div style={{display:"flex",flexDirection:"column"}}>
<label htmlFor="first">First</label>
<input onChange={onChange} defaultValue={first} name='first' id="first" type="number"/>
<label htmlFor="second">Second</label>
<input onChange={onChange} defaultValue={second} name="second" id="second" type="number"/>
<label htmlFor="sum">Total</label>
<input onChange={onChange} defaultValue={sum} id="sum" name="sum" type="number"/>
</div>
</form> );
}
export default Calculations;
解决方案
在测试您的代码后,我发现主要问题是每个输入的“defaultValue”属性。
根据官方文档here,“在组件安装后更改 defaultValue 属性的值不会导致 DOM 中的值发生任何更新。”。因此,在第一次计算之后,您的输入被视为已安装,这就是您的代码第一次工作而不是之后工作的原因。
首先,您应该将“defaultValue”更改为“value”,但这会在您的代码中产生其他逻辑问题,并且不适用于这种简单的更改。
接下来,您应该更新您在 onChange 中输入的值,但是在没有条件的情况下使用函数 calcSum()、calcFirst() 和 calcSecond() 会产生其他问题。
const onChange=(e)=>{
let name=e.target.name;
let value=e.target.value;
const newValues = {
...values,
[name]: value
}
switch (name) {
case 'first':
setFirst(value)
break;
case 'second':
setSecond(value)
break;
case 'sum':
setSum(value)
break;
}
setValues(newValues)
// calcSum(newValues)
// calcfirst(newValues)
// calcSecond(newValues)
}
然后,需要建立一些优先条件,避免同时调用 3 个 calc 函数。
您还可以在不同的函数中设置每个值,然后执行其他操作。
我希望这可以帮助你。
推荐阅读
- ddev - 如何在边车容器中使用 node-sass scss 在 ddev 项目中自动构建 CSS?
- c# - Blazor select-like 组件不更新数据源中的值
- javascript - 如何从在 switch case 语句中运行的函数返回值?
- templates - 使用 Netsuite 高级 PDF/HTML 模板进行条件打印(零值)
- namespaces - 如何使用 Jena 将远程词汇表/命名空间包含到 OntModel?
- java - 如何将新的 relic java 代理添加到 heroku 战争
- html - 如何在Angular中仅打印错误消息
- javascript - 我的 firebase 云函数不执行插入表格行的嵌套 foreach 中的代码
- c - 为什么输出是这样的?
- javascript - REST API 调用从 curl 或 python 成功,但在浏览器中失败