如何解决反应输入清除占位符
我在所有页面上都有输入。 我正在尝试在将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>
</>
);
}
解决方法
如果要清除表单,则不要设置状态,然后直接从handleSuggestionClick
函数的参数中使用它。
const handleSuggestionClick = item => {
localStorage.setItem("myLocalStore",JSON.stringify(item));
pushLocation(`/centre/${item.codeSchool}`);
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。