2 回答
TA贡献1824条经验 获得超8个赞
handleCityCheckbox = (param1) => {
const { cityList = [] } = this.state;
const itemIndex = cityList.indexOf(param1);
if (itemIndex === -1)) {
cityList.push(param1);
} else {
cityList = cityList.filter((e, index) => index !== itemIndex)
}
this.setState({ cityList });
};
TA贡献1816条经验 获得超6个赞
过滤功能:
const handleSubmit = (event) => {
event.preventDefault();
if (!name) {
alert("Enter the city name");
return;
}
let tempList = cities.filter(
(city) => city.toLowerCase() !== name.toLowerCase()
);
if (tempList.length === cities.length) {
tempList.push(name);
setCities(tempList);
return;
} else {
setCities(tempList);
}
};
在上面的函数中,我们首先使用filter函数过滤掉城市名称,如果存在则删除并赋值给,然后与主列表tempList比较 的大小,如果相同则说明该城市名称不存在于主列表中,因此我们将其推送到并使用 modded更新状态,否则,我们只需设置过滤掉的。tempListcitiesnametempListcitiestempListtempList
完整示例:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [cities, setCities] = useState(["Pune", "Delhi"]);
const [name, setName] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
if (!name) {
alert("Enter the city name");
return;
}
let tempList = cities.filter(
(city) => city.toLowerCase() !== name.toLowerCase()
);
if (tempList.length === cities.length) {
tempList.push(name);
setCities(tempList);
return;
} else {
setCities(tempList);
}
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input onChange={(event) => setName(event.target.value)} />
<button type="submit">Submit</button>
</form>
{cities.map((city) => (
<p>{city}</p>
))}
</div>
);
}
添加回答
举报