【问题标题】:Set model state with React Hooks in form inputs在表单输入中使用 React Hooks 设置模型状态
【发布时间】:2026-01-31 18:45:02
【问题描述】:

如何使用 React Hooks 中内置的 setState() 函数来更改模型的状态以进行表单输入?

例如如何在输入字段中绑定setFirstName()onChange

import React, { useState } from 'react';

const Demo = () => {
   const [ firstName, setFirstName ] = useState('');

   return (
     <div>
       <form>
        <input className="input" name="firstname" value={firstName} 
         //what do i put in onChange here?
          onChange=? />
        </form>
     </div>
   );
}




【问题讨论】:

    标签: reactjs forms setstate react-hooks


    【解决方案1】:
    import React, { useState } from 'react';
    const App = () => {
    
       //Initialize to empty string
       const [ firstName, setFirstName ] = useState("");
    
       const handleSubmit = () => {
          //You should be able console log firstName here
          console.log(firstName)
       }
    
       return (
         <div>
           <form>
            <input className="input" name="firstname" value={firstName} 
              onChange={e => setFirstName(e.target.value)} />
            <button type="submit" onClick={handleSubmit}>Submit</button>
           </form>
         </div>
    
        );
    }
    

    【讨论】: