在表单输入中使用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>
);
}


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>
);
}

相关内容

  • 没有找到相关文章

最新更新