javascript - 如何在地图功能中只打印一次按钮仍然能够访问迭代值?
问题描述
我在 material-ui 中使用 formik 作为表单。我创建了一个用于打印文本字段的地图功能。现在,我只想显示一次提交按钮,我也通过定位索引来实现。但问题是,当我尝试访问迭代项目时,我只能访问最后一个项目
我的代码:
{["Name", "E-Mail", "Phone"].map(
(item, index, arrLength) => {
let tempItem = tempItem.toLowerCase().replace("-", "");
return (
<Fragment key={index}>
<Grid item>
<TextField
variant="outlined"
id={tempItem}
name={tempItem}
label={item}
onChange={formik.handleChange}
error={
formik.touched.tempItem
? formik.touched.tempItem&&
Boolean(formik.errors.tempItem)
: null
}
/>
</Grid>
{arrLength.length - 1 === index && (
<Grid item>
<Button
disabled={formik.errors.tempItem ? true : false}
color="primary"
variant="contained"
type="submit"
>
Submit /* when I am trying to access the item and tempItem only the last of
array is being accessible. As I am using formik to show errors, when I am
clicking the submit button it should check error in all other fields, and if
no errors then only the button should display, but in this case, the button
checks only the last field(phone) and if its valid, submit button is showing
even though the other fields are invalid */
</Button>
</Grid>
)}
</Fragment>
解决方案
您不必映射到整个表单,只需TextField
像这样映射:
return (
<Fragment>
{["Name", "E-Mail", "Phone"].map((item,index) => {
let tempItem = tempItem.toLowerCase().replace("-", "");
return (
<Grid item key={index}>
<TextField
variant="outlined"
id={tempItem}
name={tempItem}
label={item}
onChange={formik.handleChange}
error={
formik.touched.tempItem
? formik.touched.tempItem && Boolean(formik.errors.tempItem)
: null
}
/>
</Grid>
)})}
<Grid item>
<Button
disabled={formik.errors ? true : false}
color="primary"
variant="contained"
type="submit"
>
Submit /* when I am trying to access the item and tempItem only the
last of array is being accessible. As I am using formik to show
errors, when I am clicking the submit button it should check error in
all other fields, and if no errors then only the button should
display, but in this case, the button checks only the last
field(phone) and if its valid, submit button is showing even though
the other fields are invalid */
</Button>
</Grid>
</Fragment>
);
推荐阅读
- python - Pytesseract OCR 错误文本识别
- r - 如何使用 R 在大型数据帧中加速 forloop grep
- python - Pygame - 从图像的 x 和 y 坐标进行 blitting
- php - dyld:Apple M1 上 php oic8 的惰性符号绑定失败
- php - 为什么这些简单的 Laravel 查询这么慢?
- kotlin - 在 kotlin 中使用 getter 和 setter 时出错
- python-3.x - 对于这个特定示例,如何在 python 中进行字符串格式化
- tensorflow - 超过 grpc 截止日期的部署 tf-serving 问题
- python - 如何编写 python 脚本以在 Window 中运行现有的任务调度程序
- javascript - Lambda@Edge 在源请求上设置 Cookie