我的问题是我创建了自定义钩子,并使用表单钩子跟踪输入的文本并更新了状态。我想在单击按钮后使用该自定义钩子提交输入值,并且状态停留在这里...
export const useForm = (initialValue) => {
const [value, setValue] = useState(initialValue);
return [value, e =>
setValue({
...value, [e.target.name] : e.target.value
})];
}
这是我的自定义钩子
<form onSubmit={updateCityName}>
<div className="form">
<div className="input-field">
<i className="material-icons prefix">location_on</i>
<input id="icon_prefix" type="text" name="cityName" value={value.cityName} onChange={handleChange} className="validate" />
<label htmlFor ="icon_prefix">City Name</label>
</div>
<button className="btn waves-effect waves-light" type="submit" name="action">Submit</button>
</div>
</form>
这是我的表格,这是函数
const updateCityName = e => {
e.preventDefault();
handleChange('what i must here type for update state???');
}
答案 0 :(得分:1)
您可以在此示例中执行以下操作: https://codesandbox.io/s/ecstatic-tree-2893r
您有useForm
来设置和更新表单状态。
然后,您具有提交状态的第二种状态。
我使用了2种不同的状态:第一个useForm
处理输入的更改。
然后,在第二状态下,一旦用户单击按钮,保留提交的信息。当然,在实际情况下,您将对提交的信息进行其他操作,例如调用网络服务等。