[英]Read (NOT SET) focus on an input in React?
谷歌沒有幫助解決的奇怪問題......如果輸入集中在 React 中,我該如何閱讀?
如果輸入沒有聚焦,我想要做的是隱藏我創建的自動完成 div。 有沒有辦法做到這一點?
就像現在一樣,如果您在文本輸入中留下一些內容並且不單擊自動完成建議之一,那么即使在移動到搜索結果和詳細信息頁面之后,自動完成 div 也會保留在那里。
我已經嘗試過首先弄亂 div 的顯示方式(一旦用戶開始輸入,它就會渲染,它會在 state 數組中設置選項),方法是將它在提交時從無到有的數組設置,但它也給了我許多呈現錯誤。
這是表格:
<form className="input-group mb-3" onSubmit={submit()}>
<input
type="text"
className="form-control mr-sm-2"
onChange={e => onSearch(e)}
placeholder="Search to follow the money"
value={searchedValue}
/>
<Link to={`/searchresults/${selected}`} selected={selected}>
<button
type="submit"
className="btn btn-light my-2 my-sm-0 shadow-sm"
style={{
height: "40px",
borderRadius: "0px",
MozBorderRadius: "0px",
WebkitBorderRadius: "0px"
}}
>
<img
alt="search-icon"
src={require("../../assets/its-a-bribe-search-punch-01.png")}
style={{ width: "24px" }}
/>
</button>
</Link>
</form>
自動完成 div 如下所示:
<div className="container auto-complete-container">{renderSugs()}</div>
onSubmit 目前就是這樣:
const submit = () => {
// setSuggestions([]);
}
如果我取消注釋 setSuggestions 它只會給我太多渲染錯誤,即使尚未提交表單?
這是我的 onSearch function:
const onSearch = e => {
setSearchedValue(e.target.value);
const value = e.target.value;
let suggestions = [];
if (value.length) {
suggestions = options.filter(option => {
var name = option.name;
// console.log("option", option)
return name.toLowerCase().includes(searchedValue.toLowerCase());
});
}
setSuggestions(suggestions);
};
為了呈現建議,我有一個名為 renderSugs 的 function 映射建議並為每個建議顯示:
<Link
key={item.id + Math.random() * 100}
to={`/politician/${item.id}`}
style={{ textDecoration: "none", color: "black" }}
>
<li
onClick={() => {
setSearchedValue(item.name);
setSuggestions([]);
}}
>
{item.name}
</li>
</Link>
在 onClick 中,你會看到我正在做一個 setSuggestions,它在這里工作得很好。 但是當我在 onSubmit 中嘗試同樣的事情時它不起作用???
幫助?
假設它是基於 class 的組件(因為您標記了問題state
),您可以這樣做。
將建議 div 包裝成這樣的條件
{this.state.showSuggestions && <div className="container auto-complete-container">{renderSugs()}</div>}
並在您的輸入中添加onFocus
和onBlur
<input
type="text"
className="form-control mr-sm-2"
onChange={e => onSearch(e)}
placeholder="Search to follow the money"
value={searchedValue}
onFocus={() => this.setState({showSuggestions: true})}
/>
<Link
key={item.id + Math.random() * 100}
to={`/politician/${item.id}`}
style={{ textDecoration: "none", color: "black" }}
>
<li
onClick={ async () => {
await setSearchedValue(item.name);
await setSuggestions([]);
this.setState({showSuggestions: false})}
}}
>
{item.name}
</li>
</Link>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.