使用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>