1

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

例如如何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>
   );
}




4

1 回答 1

3
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>

    );
}
于 2018-12-06T05:56:03.803 回答