使用React編寫過濾功能的函數
P粉596191963
P粉596191963 2023-08-16 20:02:19
0
1
584
<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粉596191963
P粉596191963

全部回覆(1)
P粉431220279

在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沒有被使用,這讓你感覺什麼都沒發生)

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板