我正在尝试在提交表单后从子组件更新父组件上共享值的状态:
父母
const [search, setSearch] = useState("default");
function handleSubmitted(n) {
setSearch(n);
console.log(search); //Doesn't update, and value lost after refresh
}
return (
<>
<Switch>
<Route exact path="/">
<Landing onSubmit={handleSubmitted} /> //Child responsible to update state
</Route>
<Route path="/add">
<Add />
</Route>
<Route path="/menus">
<RestaurantList search={search} /> //Receives updated state after a redirect
</Route>
</Switch>
</>
);
儿童
export default function Landing(props) {
return (
<>
<section className="center fullpage" id="landing">
<div className="landing__contents">
<h1>DineIn</h1>
<div className="search">
<form onSubmit={props.onSubmit} > //Call function on parent
<input type="text" placeholder="D Spot Cafe" />
</form>
</div>
</div>
</section>
</>
);
}
I'm trying to get <RestaurantList />
to receive the search value typed by the user in <Landing />
to perform the actual search query functions, but the states are not changing.
我的结构完全错误吗?
由于您的示例不是完整的示例,因此我尝试为您提供一个示例,以通过子组件的形式更改父组件的状态,并且该状态用于该父组件的另一个子组件
父组件
子组件
同级组件
The onSubmit event on
<form>
element will fire only if you put a submit button inside it and then you push it.If you want to change the state as you type on the text input, then you need to listen to the
onChange
event on the input text element. So, you'll have something like this:请注意,您还需要将搜索值传递给子组件。