我在使用 react 構建的應用程式中有一個簡單的函式,它在onClick event. map()當用戶單擊“添加按鈕”時,我正在使用添加更多欄位。將map()被重新調整表單文本欄位兩次,當我需要它只是回傳,當用戶點擊了一次add employees button。如何編輯代碼以僅在文本欄位上回傳?
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;
uj5u.com熱心網友回復:
我相信我有你的代碼作業在這里的代碼沙箱。
你的問題是你用輸入物件初始化你的狀態,直到你添加了第二個(“重復”)輸入物件,然后兩個輸入物件才被顯示。
為了解決這個問題,我所做的只是將初始狀態設定為一個空陣列,
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>
);
})}
uj5u.com熱心網友回復:
更改setInput([...input, { empName: "" }]);為setInput(prevState => [...prevState, { empName: "" }]);可能會有所幫助。狀態更新是異步的,因此當您根據之前的狀態進行更新時,最好傳遞一個函式而不是一個值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360492.html
標籤:javascript 反应
上一篇:狀態變化的直接更新(React)
