reactjs event.preventDefault()在React中不起作用

fnatzsnv  于 2022-11-22  发布在  React
关注(0)|答案(1)|浏览(167)

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

以下附件是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);
  };

  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;
bis0qfac

bis0qfac1#

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>
  );

相关问题