使用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-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} />
{/* ... */}
{children}
</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>