簡體   English   中英

單擊按鈕時,我無法從列表中搜索項目

[英]When click on button I am not able to search item from list

當我在文本框中輸入內容並單擊搜索按鈕時,它會顯示該項目

在此處輸入圖像描述

單擊按鈕時,我無法從列表中搜索項目。 我可以直接搜索項目而無需單擊按鈕,但我想搜索項目時

 this.state = { list: [], search: '', } componentDidMount(){ axios.get("https://restcountries.eu/rest/v2/region/africa").then(res=> { this.setState({list: res.data}) }) } <label className="text-secondary">Search by: </label>&nbsp; <input type="text" value={this.state.search} onChange={this.valueChange}> </input>&nbsp; valueChange = (event) =>{ this.setState({search: event.target.value}) } <button type="button" className="btn btn-info" onClick=this.search}>Search</button> search = () =>{ this.state.list.filter( (item) => { return item.name.toLowerCase().indexOf(this.state.search.toLowerCase()).== -1 || item.capital.toLowerCase().indexOf(this.state.search.toLowerCase()).== -1 || item.alpha3Code.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1 } ) }

您應該做的是將搜索邏輯移動到 function 並設置 onclick 偵聽器以觸發此 function。

像這樣的東西:

function SomeComponent(props){
  const [keyword, setKeyword] = useState("");

  const handler = () => {
    // Put your search logic here
    alert(`Do the search by ${keyword}`);
  };

  return (
    <div className="App">
      <input value={keyword} onInput={e => setKeyword(e.target.value)} />
      <br />
      <br />
      <button onClick={handler}>Search</button>
    </div>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM