首頁  >  問答  >  主體

使用React編寫過濾功能的函數

<p>我想建立一個過濾函數,當在react useState中接收到輸入值事件時觸發,但是當我開始輸入時,我看不到它做任何事情。這是我的Search組件</p> <pre class="brush:php;toolbar:false;">export function Search({categories, onSearch}){ const [searchText, setSearchText] = useState(''); const filterCategories = () => { const filteredCategories = categories.filter(category => category.name.toLowerCase().includes(searchText.toLowerCase()) ); onSearch(filteredCategories); }; const handleInputChange = event => { setSearchText(event.target.value); filterCategories(); }; return ( <div className="flex items-center"> <form className='flex space-x-1' > <input type="text" className="block w-full px-4 py-2 text-purple-700 bg-white border rounded-full focus:border-purple-400 focus:ring-purple-300 focus:outline-none focus:ring focus:ring-purple-300 focus:outline-none focus:ring focus:ring-purple-300 focus:outline-none focus:ring focus:ring -opacity-40" placeholder="搜尋..." value={searchText} onChange={handleInputChange} /> </form> </div> ) }</pre> <p>然後在這裡使用</p> <pre class="brush:php;toolbar:false;">const Layout = ({ categories, children }) => { const [filteredCategories, setFilteredCategories] = useState(categories); const handleSearch = (filteredCategories) => { setFilteredCategories(filteredCategories); }; return ( <div> {/* ... */} <Search categories={categories} onSearch={handleSearch} /> {/* ... */} {孩子} </div> ); }; export default Layout;</pre> <p>然後這個元件被用在Home元件中</p> <pre class="brush:php;toolbar:false;">export default function Home({ posts, categories }) { return ( <Layout categories={categories}> <div className="mt-20"> <main className="flex flex-col justify-center items-center h-screen pt-10 pb-30"> {/* 渲染貼文 */} </main> </div> </Layout> ); }</pre> <p>我該做些什麼才能讓它運作嗎? </p>
P粉596191963P粉596191963453 天前549

全部回覆(1)我來回復

  • P粉431220279

    P粉4312202792023-08-17 14:42:05

    在Layout元件中,你正在將categories的值傳遞給你的Search元件,你可能想要傳遞filteredCategories

    const Layout = ({ categories, children }) => {
      const [filteredCategories, setFilteredCategories] = useState(categories);
    
      const handleSearch = (filteredCategories) => {
        setFilteredCategories(filteredCategories);
      };
    
      return (
        <div>
          {/* ... */}
          <Search
            categories={filteredCategories} // 这里
            onSearch={handleSearch}
          />
          {/* ... */}
          {children}
        </div>
      );
    };
    
    export default Layout;

    (filteredCategories沒有被使用,這讓你感覺什麼都沒發生)

    回覆
    0
  • 取消回覆