简体   繁体   English

我正在使用 React-Bootstrap。 e.preventDefault() 不起作用

[英]I'm using React-Bootstrap. The e.preventDefault() is not working

I'm trying to put a simple Search Box in my navbar.我正在尝试在我的导航栏中放置一个简单的搜索框。 I'm using React-Bootstrap, with python and django.我正在使用 React-Bootstrap,带有 python 和 django。 So, I want to prevent default form behaivor: e.preventDefault();所以,我想防止默认形式行为:e.preventDefault();

The problem is: it is not working.问题是:它不起作用。 If I hit enter on the form or if I click the button, the page refreshes and the console.log("hello there I am working") doesn't show.如果我在表单上按 Enter 或单击按钮,页面会刷新并且 console.log("hello there I am working") 不会显示。 Why?为什么?

Code:代码:



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;

Maybe the refresh is because of history.也许刷新是因为历史。 I tried running your code by commenting out the history commands in a sandbox and it is working fine.我尝试通过在沙箱中注释掉历史命令来运行您的代码,它工作正常。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM