javascript 单击后React搜索栏筛选器

lawou6xi  于 2022-12-28  发布在  Java
关注(0)|答案(1)|浏览(146)

我有一个过滤器来搜索产品,但它会在我键入产品名称后直接搜索。
我的代码

const [searchTerm, setSearchTerm] = useState("");
    const [product, setProduct] = useState([]); 

    const displayProduct = product
    .filter((product)=>{
        if (searchTerm == ""){
            return product
        }else if(product.productName.replaceAll(/\s/g,'').toLowerCase().includes(searchTerm.toLowerCase().replaceAll(/\s/g,''))){
            return product
        }
    })
    .slice(pagesVisited,pagesVisited + productPerPage)
    .map(product => {
        return(
            <div className='imageContainer ' key={product.id}>
                <img src={PopularOne} className="image"/>
                <div className='productName'>
                <Link style={{ textDecoration:'none' }} to="/productsDetails" state={{ product:product }}>{product.productName}</Link>
                </div>
                <div className='productPrice'>
                <h3 >RM{product.productPrice}</h3>
                </div>
            </div>   
        )
    })

   <div>
     <input className='filterInput' onChange={event => 
     {setSearchTerm(event.target.value)}}></input>
     <button className='filterSearchButton'>Search</button>
   </div>

我如何让它在我单击按钮后过滤?

8cdiaqws

8cdiaqws1#

我已添加单击按钮
onClick调用handleFilter以筛选数据
我还添加了新的seState以设置筛选的数据

const [searchTerm, setSearchTerm] = useState("");
const [displayProduct, setDisplayProduct] = useState(product || []);

const handleFilter = () => {
  const _displayProduct = product
  .filter((product)=>{
      if (searchTerm == ""){
          return product
      }else if(product.productName.replaceAll(/\s/g,'').toLowerCase().includes(searchTerm.toLowerCase().replaceAll(/\s/g,''))){
          return product
      }
  })
  .slice(pagesVisited,pagesVisited + productPerPage)
  .map(product => {
      return(
          <div className='imageContainer ' key={product.id}>
              <img src={PopularOne} className="image"/>
              <div className='productName'>
              <Link style={{ textDecoration:'none' }} to="/productsDetails" state={{ product:product }}>{product.productName}</Link>
              </div>
              <div className='productPrice'>
              <h3 >RM{product.productPrice}</h3>
              </div>
          </div>   
      )
  })
  setDisplayProduct(_displayProduct);
}

<div>
 <input className='filterInput' onChange={event => 
 {setSearchTerm(event.target.value)}}></input>
 <button className='filterSearchButton' onClick={handleFilter}>Search</button>
</div>

相关问题