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