【问题标题】:event.preventDefault( ) is NOT working in Reactevent.preventDefault() 在 React 中不起作用
【发布时间】:2022-01-02 13:21:57
【问题描述】:

无法在控制台中获取值! 我做错了什么?

下面附上React的功能组件

处理函数

import React, { useState, useRef } from 'react';

const SimpleInput = (props) => {
  const nameInputRef = useRef();
  const [enteredName, setEnteredName] = useState('');

  const nameInputChangeHandler = (event) => {
    setEnteredName(event.target.value);
  };

  const formSubmissionHandler = (event) => {
    event.preventDefault();
    console.log(enteredName);

    const enteredName = nameInputRef.current.value;
    console.log(enteredName);
  };

JSX 代码

  return (
    <form>
      <div className="form-control" onSubmit={formSubmissionHandler}>
        <label htmlFor="name">Your Name</label>
        <input
          ref={nameInputRef}
          type="text"
          id="name"
          onChange={nameInputChangeHandler}
        />
      </div>
      <div className="form-actions">
        <button>Submit</button>
      </div>
    </form>
  );
};

export default SimpleInput;

【问题讨论】:

  • form 元素上添加onSubmit={formSubmissionHandler}

标签: reactjs forms react-hooks preventdefault


【解决方案1】:

formSubmissionHandler 应该位于 form 元素上,而不是 div 元素上。

 return (
    <form onSubmit={formSubmissionHandler}>
      <div className="form-control">
        <label htmlFor="name">Your Name</label>
        <input
          ref={nameInputRef}
          type="text"
          id="name"
          onChange={nameInputChangeHandler}
        />
      </div>
      <div className="form-actions">
        <button>Submit</button>
      </div>
    </form>
  );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多