React表单提交触发onSubmit时history.push路由跳转不生效如何解决
问题原因
- 事件绑定位置错误:
onSubmit是<form>标签的专属事件,绑定到提交按钮(IconButton)上不会触发,按钮对应的交互事件是onClick - 未阻止表单默认提交行为:原生表单提交默认会触发页面刷新、跳转,会覆盖React路由的客户端跳转逻辑,必须调用
e.preventDefault()阻止默认行为 - 输入框取值逻辑错误:提交事件触发时
e.target指向触发事件的元素,如果直接绑定到按钮上无法拿到输入框内容,绑定到form上也需要从表单字段中取值,不能直接读e.target.value
修复方案
修改后的搜索组件代码如下:
const SearchAppBar = (props) => { const { history, onPlatformDrop, onPlatformChange, onPriceRangeDrop, clearPriceRange, searchQuery, setSearchQuery, clearGenre, onDropDownChange, } = props; const handleSubmit = (e) => { // 阻止原生表单提交的默认行为 e.preventDefault(); history.push("/find"); clearGenre(); clearPriceRange(); onPlatformChange(""); onPlatformDrop("All Platforms"); onPriceRangeDrop("All Price Range"); onDropDownChange("All Genres"); }; return ( <Box sx={{ flexGrow: 1 }}> <Search sx={{ width: { xs: "85vw", md: "50vw", lg: "30vw" }, margin: "auto", marginBottom: "20px", }} > {/* onSubmit绑定到form元素,移除原生的action、method属性 */} <form onSubmit={handleSubmit} style={{ display: "flex" }}> <StyledInputBase // 改成受控组件,实时同步输入值到状态 value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} autoComplete="off" placeholder="Search All Games…" inputProps={{ "aria-label": "search" }} type="search" name="s" id="site-search" /> <SearchIconWrapper> <IconButton type="submit"> <SearchIcon style={{ color: "#55597d" }} /> </IconButton> </SearchIconWrapper> </form> </Search> </Box> ); }; export default withRouter(SearchAppBar);
额外注意事项
- 检查App路由中渲染的
<Search>组件是否和当前导出的SearchAppBar是同一个组件,避免名称不匹配导致渲染异常 - 如果你使用的是React Router v6及以上版本,
withRouter已经被官方移除,建议直接使用useNavigate钩子替代history.push,写法更简洁
内容的提问来源于stack exchange,提问作者Forged
相关产品推荐
相关产品推荐

