我在使用 React 构建的应用程序中有一个简单的函数,它在 onClick 事件
上添加了一个表单文本字段。当用户单击“添加按钮”时,我使用 map()
添加更多字段。当我需要在用户单击“添加员工”按钮时返回一次时,map()
会重新调整表单文本字段两次。如何编辑代码以仅在文本字段上返回?
import { React, useState } from "react";
import { Button, Form } from "react-bootstrap";
import { Col } from "react-bootstrap";
import { Row } from "react-bootstrap";
const EmployeeName = () => {
const [input, setInput] = useState([{ empName: "" }]);
const AddInputField = () => {
setInput([...input, { empName: "" }]);
};
const RemoveInput = (i) => {
const inputList = [...input];
inputList.splice(i, 1);
setInput(inputList);
}
return (
<>
{input.length === 1 ? (
<Button style={{ display: "inline" }} onClick={AddInputField}>
click here to add company employees
</Button>
) : (
<Button style={{ display: "none" }}>
click here to add company employees
</Button>
)}
{input.length !== 1 &&
input.map((value, i) => {
return (
<Row>
<Col>
<Form.Group>
<Form.Control
key={i}
value={value.empName}
name="empName"
type="text"
placeholder="Add Employee Name"
/>
</Form.Group>
</Col>
<Col>
<Button
onClick={AddInputField}
>
Add
</Button>
<Button
onClick={() => RemoveInput(i)}
>
Remove
</Button>
</Col>
</Row>
);
})}
</>
);
};
export default EmployeeName;
最佳答案
我相信我让您的代码在代码沙箱中运行 here。
您的问题是,您使用输入对象初始化了状态,但在添加第二个(“重复”)输入对象之后,该输入对象才会显示,然后两者都会呈现。
为了解决这个问题,我所做的就是将初始状态设置为空数组,
const [input, setInput] = useState([]);
并更改条件逻辑以补偿不同的长度。
{input.length < 1 ? (
<Button style={{ display: "inline" }} onClick={AddInputField}>
click here to add company employees
</Button>
) : (
<Button style={{ display: "none" }}>
click here to add company employees
</Button>
)}
{input.length > 0 &&
input.map((value, i) => {
return (
<Row>
<Col>
<Form.Group>
<Form.Control
key={i}
value={value.empName}
name="empName"
type="text"
placeholder="Add Employee Name"
/>
</Form.Group>
</Col>
<Col>
<Button onClick={AddInputField}>Add</Button>
<Button onClick={() => RemoveInput(i)}>Remove</Button>
</Col>
</Row>
);
})}
关于javascript - Map() 返回重复组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70027004/