react 获取表单中输入框的值

通过使用useState钩子来创建一个状态变量,你可以同时获取多个Input框的值。

1获取input框的值:

import React, { useState } from 'react';

function MyComponent() {
  const [forms, setForms] = useState({
    name: '',
    nation: '',
  });

  const handleInputChange = (e) => {
    const { name, value } = e.target;

    setForms((prevForms) => ({
      ...prevForms,
      [name]: value,
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    console.log('姓名:', forms.name);
    console.log('国家:', forms.nation);

    // 执行其他逻辑
  };

  return (
    
{/* 添加其他Input框 */}
); } export default MyComponent;

2获取select框的值

import { useState } from 'react';
import { Select } from 'antd';

const { Option } = Select;

const YourComponent = () => {
  const [forms, setForms] = useState({
    name: "",
    nation: ""
  });

  const handleNameChange = (value) => {
    setForms(prevState => ({
      ...prevState,
      name: value
    }));
  };

  const handleNationChange = (value) => {
    setForms(prevState => ({
      ...prevState,
      nation: value
    }));
  };

  return (
    <>
      

      
    
  );
};

你可能感兴趣的:(react.js,前端)