在表单输入中使用React Hooks设置模型状态

时间:2018-12-06 05:50:55

标签: reactjs forms setstate react-hooks

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




1 个答案:

答案 0 :(得分: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>

    );
}

在此之前,请确保您已完成npm install react@next react-dom@next以获得React Hooks库。

编辑(2019年3月3日): React Hooks是React 16.8中的新增功能