I have 2 child components: a Categories
select and a Search
input text and submit button. They both have their own state. I have to use those two components in a parent page. I need to know in which category I have to do the search and to achieve this I think I should lift the state, so that the parent will handle it.
基本上,我从子组件中删除了状态,并将其放置在父组件上,最终得到了这样的代码(简化的代码):
export default ParentPage = () => {
const [searchString, setSearchString] = useState("");
const [category, setCategory] = useState(0);
const onSearch = () => {
// search for searchString in the selected category
}
return (
<>
<Categories category={category} setCategory={setCategory} />
<Search searchString={searchString} setSearchString={setSearchString} onSearch={onSearch} />
</>
)
}
这是一个好方法吗?似乎有些冗长,是否有更紧凑的方法将state和setState传递给子组件?