【问题标题】:e.preventDefault(); Not working (React.js)e.preventDefault();不工作(React.js)
【发布时间】:2021-12-13 04:49:36
【问题描述】:

如何阻止表单提交实际提交页面?

我尝试了e.stopPropagation();e.nativeEvent.stopImmediatePropagation();,但并没有阻止表单提交页面

import React,{useState,useRef} from 'react';
import Counter from './components/Counter';
import Сlasscounter from './components/Classcounter';
import './styles/APP.css';
import Postlist from './components/Postlist';
 import Postitem from "./components/Postitem";
 import Mybutton from "./components/UI/button/Mybutton";
 import Myinput from "./components/UI/input/Myinput";
function App() {
 const [post,setpost]=useState([
  {id:1,title:'kickstart',body:'beginner'},
  {id:2,title:'backend',body:'back'},
  {id:3,title:'frontend',body:'description'},
  {id:4,title:'fullstack',body:'description'},
  {id:5,title:'architets',body:'description'},
  {id:6,title:'coding',body:'description'}
 ])
 const [title,setTitle]=useState('');
 const [body,setBody]=useState('');
 const addNewPost=function(e){
  /* e.stopPropagation();
  e.nativeEvent.stopImmediatePropagation(); */
  e.preventDefault();
   const newpost={
     title,
     body
   };
 console.log(newpost);
 };
  return (
    <div className="App">
       <form>
         <Myinput     
          value={title}
          onChange={e => setTitle(e.target.value)}
          type="text"
           placeholder="Description"/>
         <Myinput 
          type="text"
          placeholder="Description"
          value={body}
          onChange={e => setBody(e.target.value)}
          type="text"
           placeholder="Description"/>
          <Mybutton onclick={addNewPost}>Створити пост</Mybutton>       
       </form>
    </div>
  );
}
export default App;

Problem is that after i click on button everything refresh

【问题讨论】:

  • 现在您的事件是按钮单击事件,而不是表单提交事件。所以解决方案是将处理程序移动到表单。 &lt;form onSubmit={addNewPost}&gt; 并将按钮定义为提交类型,以便在点击时触发表单提交&lt;button type="submit"&gt;
  • Mybutton 组件是什么样的?我会说问题出在那儿
  • 我试试这个,但没用 发帖
    不知道为什么它不起作用

标签: javascript reactjs web events web-site-project


【解决方案1】:

试试

<form onSubmit={addNewPost}>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2019-10-26
    • 1970-01-01
    相关资源
    最近更新 更多