ReactJs 我的 event.preventDefault();不起作用

发布于 2025-01-17 12:49:16 字数 2003 浏览 0 评论 0原文

我尝试在 React js 上创建一个表单,但我不想在提交表单时刷新页面。

我在我的服务器(烧瓶)上进行回调。

当我尝试执行以下操作时:“event.preventDefault();”我对 Flask 服务器的调用不起作用。

这是我的代码:

import { useState } from 'react';


const Form = (props) => {

  const componentDidMount = (event) => {
      event.preventDefault();

    // Simple POST request with a JSON body using fetch
    
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: title })
    };
    
    fetch('http://localhost:5000/add', requestOptions)
    
        .then(response => response.json())
        
        .catch(error => console.log(error))
        
      
  }
  const [title, setTitle] = useState('')
  const [body, setBody] = useState('')


return (
     <div>
        <form onSubmit = {() => componentDidMount()} >

            <label htmlFor="title" className="form-label">Title</label>
                    <input 
                    type="text"
                    className="form-control" 
                    placeholder ="Enter title"
                    value={title}
                    onChange={(e)=>setTitle(e.target.value)}
                    required
                    />

                    <label htmlFor="body" className="form-label">Body</label>
                    <textarea 
                    className="form-control" 
                    placeholder ="Enter body" 
                    value={body}
                    onChange={(e)=>setBody(e.target.value)}
                    required
                    >
                    </textarea>

                    <button 
                    className="btn btn-primary mt-2"
                    >
                    Publish article</button>

                    </form>
    </div>
)}

export default Form;

我不想刷新页面,因为我的回调函数有二分之一,我想处理它,但我无法读取控制台上的错误。

感谢您的帮助!

i try to do a form on react js and i don't want to refresh the page when i submit my form.

I do a callback on my server (flask).

When i try to do :"event.preventDefault();" my call to my flask server doesn't work.

there is my code:

import { useState } from 'react';


const Form = (props) => {

  const componentDidMount = (event) => {
      event.preventDefault();

    // Simple POST request with a JSON body using fetch
    
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: title })
    };
    
    fetch('http://localhost:5000/add', requestOptions)
    
        .then(response => response.json())
        
        .catch(error => console.log(error))
        
      
  }
  const [title, setTitle] = useState('')
  const [body, setBody] = useState('')


return (
     <div>
        <form onSubmit = {() => componentDidMount()} >

            <label htmlFor="title" className="form-label">Title</label>
                    <input 
                    type="text"
                    className="form-control" 
                    placeholder ="Enter title"
                    value={title}
                    onChange={(e)=>setTitle(e.target.value)}
                    required
                    />

                    <label htmlFor="body" className="form-label">Body</label>
                    <textarea 
                    className="form-control" 
                    placeholder ="Enter body" 
                    value={body}
                    onChange={(e)=>setBody(e.target.value)}
                    required
                    >
                    </textarea>

                    <button 
                    className="btn btn-primary mt-2"
                    >
                    Publish article</button>

                    </form>
    </div>
)}

export default Form;

I don't want to refresh the page cause one in two my callback function and i want to work on it but i can't read the error on the console.

Thanks for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

提笔落墨 2025-01-24 12:49:16

您还需要通过事件来触发event.preventdefault()函数

<form onSubmit = {(event) => componentDidMount(event)} >

you need to pass event as well to trigger event.preventDefault() function

<form onSubmit = {(event) => componentDidMount(event)} >
诗化ㄋ丶相逢 2025-01-24 12:49:16

这是因为您在 form 标签中调用了 componentDidMount 函数。

您只需在 onSubmit 属性中传递函数的引用即可。

<form onSubmit={componentDidMount}>
...
</form>

It is because you are calling the function componentDidMount in form tag.

You just have to pass the reference of the function in the onSubmit attribute.

<form onSubmit={componentDidMount}>
...
</form>
帅气称霸 2025-01-24 12:49:16

我不建议使用组件生命周期方法(例如ComponentDidMount)来处理表单提交事件。
您可以创建一个特定的处理程序:

const Form = (props) => {

    const handleSubmit = (event) => {
        event.preventDefault();
        // ...
    }
    // ...


    return (
        <div>
            <form onSubmit={handleSubmit} > 

                {/* // ... */}
            </form>
        </div>
    )
}

I wouldn't recommend to use a component lifecycle method (like componentDidMount) to handle a form submission event.
You could just create a specific handler:

const Form = (props) => {

    const handleSubmit = (event) => {
        event.preventDefault();
        // ...
    }
    // ...


    return (
        <div>
            <form onSubmit={handleSubmit} > 

                {/* // ... */}
            </form>
        </div>
    )
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文