【发布时间】:2021-02-06 06:05:29
【问题描述】:
我在所有页面中都有输入。 在将 item.name (setSearchSchool) 发送到 handleSuggestionClick 后,我正在尝试清除输入占位符。如果我在 handleSuggestionClick 中清除 setSearchSchool,我不会进入下一页。如何清理输入占位符?
搜索组件(代码已更新)
import React, { useEffect, useState } from "react";
import api from "../../api/index";
import "./index.css";
import { useLocation } from "wouter";
export default function Search() {
const [searchSchool, setSearchShool] = useState("");
const [showSuggestions, setShowSuggestions] = useState(false);
const [allSchools, setAllSchools] = useState([]);
const [, pushLocation] = useLocation();
useEffect(() => {
(async () => {
const data = await api.getSchools();
setAllSchools(data);
})();
}, []);
const resultsAllSchools = !searchSchool
? allSchools
: allSchools
.map(item => ({
name: item.name,
codeSchool: item.codeSchool,
address: item.address,
city: item.city,
nameRegion: item.nameRegion,
codeRegion: item.codeRegion,
latitud: item.latitud,
longitud: item.longitud
}))
.filter(school => school.name.toLowerCase().includes(searchSchool));
const handleOnchange = e => {
e.preventDefault();
const lowerCase = e.target.value.toLowerCase();
setSearchShool(lowerCase);
setShowSuggestions(true);
if (e.target.value === "" || null) {
setShowSuggestions(false);
}
};
const handleSuggestionClick = item => {
setSearchShool(item.name);
localStorage.setItem("myLocalStore", JSON.stringify(item));
pushLocation(`/centre/${item.codeSchool}`);
};
return (
<>
<section className="section">
<div className="search">
<input
className="select"
type="text"
placeholder="Cerca el teu centre educatiu... "
value={searchSchool}
onChange={handleOnchange}
></input>
<div className="svg_search">
<svg
height="25"
viewBox="0 0 21 21"
width="25"
xmlns="http://www.w3.org/2000/svg"
>
<g
fill="none"
fillRule="evenodd"
stroke=" #0099ff"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="8.5" cy="8.5" r="5" />
<path d="m17.571 17.5-5.571-5.5" />
</g>
</svg>
</div>
</div>
<ul>
{showSuggestions &&
resultsAllSchools.map((item, i) => (
<li
key={i}
title={item.name}
onClick={() => handleSuggestionClick(item)}
>
<p className="school_name">{item.name}</p>
<p className="school_address">
{item.address} - {item.city}
</p>
</li>
))}
</ul>
</section>
</>
);
}
【问题讨论】:
-
你为什么在这里使用这么多州?
codeSchool、selectSchool和searchSchool,这里都是一个州,都是不同类型的学校?codeSchool基本上只是item.codeSchool而 searchSchool 只是item.name。它们是项目的一部分,它们在这里不应该是不同的状态。您可以在您的状态中设置项目并从中派生属性,例如 codeSchool 和 searchSchool。 -
您是我不需要 codeSchool 和 selectSchool 的原因,感谢您的评论。我继续遇到同样的问题。我无法清除输入占位符
-
更新上面的代码
-
完成,代码更新
-
你可以在下面看到答案。
标签: reactjs input placeholder