亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何避免在React JS中的搜索欄下一次顯示所有元素

如何避免在React JS中的搜索欄下一次顯示所有元素

忽然笑 2023-07-29 15:27:32
我嘗試了這個,甚至在輸入要搜索的值之前,所有產品都會出現在搜索欄下方,如何僅在搜索時顯示產品。請幫忙提前致謝搜索欄.jsimport React, { Component } from 'react'import {storeProducts} from '../data';import Product from './Product';import styled from 'styled-components';export default class SearchBar extends Component { constructor(){  super();  this.state={   search: '',    }; } updateSearch(event) { this.setState({search:event.target.value.substr(0,20)}) } render() {  let filteredProducts = storeProducts.filter(   (product) => {    return product.title.indexOf(this.state.search) !== -1;   }  );  return (   <SearchWrapper>   <input type="text" value={this.state.search} onChange={this.updateSearch.bind(this)} placeholder="search"/>   {filteredProducts.map((product) => {    return <li> <Product product={product} key={product.title}/></li>   })}   </SearchWrapper>  ) }}const SearchWrapper = styled.div`background:#f6f6f6;padding: 30px 200px;input{ border:1px solid #76bd05; width:40rem;}li{ height 50px; list-style:none;}`;
查看完整描述

1 回答

?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

發生這種情況是因為this.state.search最初是一個空字符串''。當您過濾您正在使用的產品時indexOf(this.state.search),這將為每個產品返回 true,因為空字符串將匹配任何內容。


我只是在渲染函數中添加一個條件。如果this.state.search.length > 0則顯示過濾后的產品。


{this.state.search.length > 0 && filteredProducts.map((product) => {

  return (

    <li>

      <Product product={product} key={product.title} />

    </li>

  );

})}


查看完整回答
反對 回復 2023-07-29
  • 1 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號