[英]I'm using React-Bootstrap. The e.preventDefault() is not working
我正在尝试在我的导航栏中放置一个简单的搜索框。 我正在使用 React-Bootstrap,带有 python 和 django。 所以,我想防止默认形式行为: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;
也许刷新是因为历史。 我尝试通过在沙箱中注释掉历史命令来运行您的代码,它工作正常。
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(`/?keyword=${keyword}&page=1`);
// }
};
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.