Javascript 将两个不同输入的值相乘,并显示在第三个输入中
我有一个表单,我正在使用Formik验证表单,当有输入时,我想将数量输入和单位成本输入上的值相乘,然后自动显示在总输入中。我正在使用Formik+脉轮Javascript 将两个不同输入的值相乘,并显示在第三个输入中,javascript,reactjs,formik,chakra-ui,Javascript,Reactjs,Formik,Chakra Ui,我有一个表单,我正在使用Formik验证表单,当有输入时,我想将数量输入和单位成本输入上的值相乘,然后自动显示在总输入中。我正在使用Formik+脉轮 <Formik initialValues={{ productName: "", productNumber: "", unitCost: 0, totalCost: 0, quant
<Formik
initialValues={{
productName: "",
productNumber: "",
unitCost: 0,
totalCost: 0,
quantity: 0,
}}
>
{({ values }) => (
<Form>
<Field name="productName">
{() => (
<Grid templateColumns="repeat(2, 1fr)" gap={5}>
<Box>
<FormControl>
<FormLabel htmlFor="productName">Product Name:</FormLabel>
<Input id="productName" placeholder="Product Name" />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
<Box>
<FormControl>
<FormLabel htmlFor="productNumber">
Product Number:
</FormLabel>
<Input id="productNumber" placeholder="Product Number" />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
<Box>
<FormControl>
<FormLabel htmlFor="quantity">Quantity:</FormLabel>
<Input id="quantity" placeholder="Quanity" />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
<Box>
<FormControl>
<FormLabel htmlFor="unitCost">Unit Cost:</FormLabel>
<Input id="unitCost" placeholder="Unit Cost" />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
<Box>
<FormControl>
<FormLabel htmlFor="totalCost">Total Cost:</FormLabel>
<Input id="totalCost" placeholder="Total Cost" />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
</Grid>
)}
</Field>
<Button isFullWidth mt={6} colorScheme="green" type="submit">
Submit
</Button>
</Form>
)}
</Formik>
{({values})=>(
{() => (
产品名称:
{/*{form.errors.name}*/}
产品编号:
{/*{form.errors.name}*/}
数量:
{/*{form.errors.name}*/}
单位成本:
{/*{form.errors.name}*/}
总成本:
{/*{form.errors.name}*/}
)}
提交
)}
要缩短状态管理的代码,只需从值中删除总成本
,并在使用时进行计算即可
更新后的代码如下所示:
<Formik
initialValues={{
productName: "",
productNumber: "",
unitCost: 0,
quantity: 0,
}}
onSubmit={...}
>
{({ values }) => (
<Form>
<Grid templateColumns="repeat(2, 1fr)" gap={5}>
// ... other boxes stay same as before
<Box>
<FormControl>
<FormLabel htmlFor="totalCost">Total Cost:</FormLabel>
<Input id="totalCost" placeholder="Total Cost" value={values.quantity * values.unitCost} />
{/* <FormErrorMessage>{form.errors.name}</FormErrorMessage> */}
</FormControl>
</Box>
</Grid>
<Button isFullWidth mt={6} colorScheme="green" type="submit">
Submit
</Button>
</Form>)}
</Formik>
此处解释了舍入:您需要的是setFieldValue方法。检查这个仍然不清楚,我会处理两个表单上的更改吗??
<FormControl>
<FormLabel htmlFor="totalCost">Total Cost:</FormLabel>
<Box id="totalCost">{Math.round((values.quantity * values.unitCos + Number.EPSILON) * 100) / 100}</Box>
</FormControl>