英文:
Why I get the error trying to lift up props?
问题
这里有一个状态,我正在尝试将它们传递到子组件SearchBar中。
App组件(父组件)
// 与问题无关的代码...
// 搜索
const { search, setSearch } = useState("");
const handleSearch = (e) => {
setSearch(e.target.value);
};
// 与问题无关的代码...
return (
<ContextProviders
// 与问题无关的代码...
>
<div className="App">
<Navbar />
<SearchBar search={search} handleSearch={(e) => handleSearch(e)} />
<Outlet />
</div>
</ContextProviders>
);
在我输入内容以触发setState时,出现错误:
SearchBar(子组件)
import { useState } from "react";
export default function SearchBar(props) {
// 与问题无关的代码...
console.log(props);
return (
<>
<div>
<input
type="search"
value={props.search}
onChange={props.handleSearch}
// 与问题无关的代码...
/>
</div>
</>
);
}
我需要将搜索组件(子组件)中输入字段的值传递到App组件(父组件)中,我尝试传递一个设置状态的函数到App中,但它不起作用,我收到错误:
Uncaught TypeError: setSearch is not a function at handleSearch
有人看到问题吗?
英文:
Here I have the state, and I am trying to pass them into child component SearchBar
App Component (parent component)
// 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>
);
}
Into SearchBar when I am typing something in order to trigger setState it shows up an error:
SearchBar (child component)
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:
>Uncaught TypeError: setSearch is not a function at handleSearch
Does anyone see the issue here?
答案1
得分: 2
你应该将你的状态初始化为:
const [search, setSearch] = useState("");
然后像这样传递handleSearch
函数:
<SearchBar search={search} handleSearch={handleSearch} />
英文:
You should initialize your state as:
const [search, setSearch] = useState("");
And pass the handleSearch
function like this:
<SearchBar search={search} handleSearch={handleSearch} />
答案2
得分: 0
你为什么在 handleSearch 中传递匿名箭头函数?只需要指向 handleSearch 函数即可,不需要调用它。
英文:
why did you pass the anonymous arrow function in handleSearch? you just need to point handleSearch function. There is no need to call it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论