如何使用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>
);
}
答案 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中的新增功能