[英]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.