使用React编写过滤功能的函数
P粉596191963
P粉596191963 2023-08-16 20:02:19
0
1
552
<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>
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没有被使用,这让你感觉什么都没有发生)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!