这里我有状态,我试图将它们传递给子组件 SearchBar
App组件(父组件)
// not related code ...
// search
const { search, setSearch } = useState("");
const handleSearch = (e) => {
setSearch(e.target.value);
};
// not related code ...
return (
<ContextProviders
// not related code ...
>
<div className="App">
<Navbar />
<SearchBar search={search} handleSearch={(e) => handleSearch(e)} />
<Outlet />
</div>
</ContextProviders>
);
}
当我输入内容以触发 setState 时进入 SearchBar,它显示错误:
SearchBar(子组件)
import { useState } from "react";
export default function SearchBar(props) {
// not related code ...
console.log(props);
return (
<>
<div>
<input
type="search"
value={props.search}
onChange={props.handleSearch}
// not related code ...
/>
</div>
</>
);
}```
I need to get the value from the input field in the search component(child) into App component(parent), I try to pass a function which sets state into App, but it doesn't work, I get the error:
**ERROR**
Uncaught TypeError: setSearch 不是一个函数 在 handleSearch
Does anyone see the issue here?
你应该将你的状态初始化为:
const [search, setSearch] = useState("");
然后像这样传递
handleSearch
函数:
<SearchBar search={search} handleSearch={handleSearch} />
为什么在handleSearch中传递了匿名箭头函数?你只需要指向 handleSearch 函数。没有必要调用它。