【发布时间】:2022-01-23 00:03:44
【问题描述】:
我正在尝试在我的导航栏中放置一个简单的搜索框。我正在使用带有 python 和 django 的 React-Bootstrap。所以,我想阻止默认形式的行为:e.preventDefault();
问题是:它不工作。如果我在表单上按 Enter 或单击按钮,页面会刷新并且 console.log("hello there I am working") 不会显示。为什么?
代码:
import React, { useState } from "react";
import { Button, Form } from "react-bootstrap";
import { useHistory } from "react-router-dom";
function SearchBox() {
const [keyword, setKeyword] = useState("");
let history = useHistory();
const submitHandler = (e) => {
e.preventDefault();
console.log("hello there I am working");
if (keyword) {
history.push(`/?keyword=${keyword}&page=1`);
} else {
history.push(history.push(history.location.pathname));
}
};
return (
<div>
<Form onSubmit={submitHandler}>
<Form.Control
type="text"
name="keyword"
onChange={(e) => setKeyword(e.target.value)}
className="mr-sm-2 ml-sm-5"
></Form.Control>
<Button type="submit" variant="outline-success" className="p-2">
Submit
</Button>
</Form>
</div>
);
}
export default SearchBox;
【问题讨论】:
-
您没有在名为
e的函数参数中获取事件参数,希望您在其中获取表单值 -
TheTisiboth:谢谢,但我的代码已经包含在表单标签中。所以,这不是问题。
-
Zain Khan:我没听懂。我已将 onChange 函数更改为:onChange={(eChange) => setKeyword(eChange.target.value)}。还是不行。页面仍在刷新。
-
@AlbertoCamposSilva 您不需要更改功能
-
而你在 history.push 函数中执行
history.push(),请在submitHandler函数中检查你的 else 条件
标签: javascript reactjs react-bootstrap page-refresh preventdefault