【问题标题】:React form refreshing the page despite being told not toReact 表单刷新页面,尽管被告知不要
【发布时间】:2023-04-11 02:15:01
【问题描述】:

我在一个反应​​项目中有一个行为有点奇怪的表单。我已将 e.preventDefault() 附加到我的提交按钮,但由于某种原因,每次单击按钮时页面仍在刷新。有人可以帮我弄清楚为什么会这样吗?这是有问题的组件:

import React, { useState } from 'react';
import './PostForm.css';
import axios from 'axios'

const PostForm = () => {

  const [posts, setPost] = useState({
    body: '',
    author: 'Michael',
  });

const onChange = (e) =>{
    setPost({...posts, [e.target.name] : e.target.value})

}

const sendPost = (e) => {
  e.preventDefault()
  try {
    const res = axios.post('http://localhost:4000/post', posts);
  console.log(res)
  } catch (error) {
    console.log(error)
    
  }
  
}

  return (
    <form className="formContainer">
      <div className="form">
        <textarea className='formBody' type="text" placeholder="What's new?" name='body' onChange={onChange} />
       
        <button onSubmit={sendPost}>Share</button>
      </div>
    </form>
  );
};

export default PostForm;

【问题讨论】:

  • onSubmit 需要在&lt;form&gt; 上,而不是随机的&lt;button&gt;

标签: javascript reactjs forms


【解决方案1】:

onSubmit 应该在表单标签中。并将按钮更改为输入,其类型为提交。

    <form className="formContainer" onSubmit={sendPost}>
      <div className="form">
        <textarea className='formBody' type="text" placeholder="What's new?" name='body' onChange={onChange} />
        <input type="submit" value="Share" />
      </div>
    </form>

【讨论】:

  • 非常感谢……就是这样的小事。我的应用程序中有几个其他表单,我没有将它们标记为表单,因此它们在上述布局中按预期工作。没想到有区别。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-28
  • 2019-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
相关资源
最近更新 更多