我正在使用 React Hooks - 重写表单以使用钩子概念。一切都按预期工作,除了一旦我在输入中输入任何 1 个字符,输入就会失去焦点。
我猜有一个问题,组件的外部不知道组件内部的变化,但是我该如何解决这个问题呢?
这是 useForm 钩子:
import React, { useState } from "react";
export default function useForm(defaultState, label) {
const [state, setState] = useState(defaultState);
const FormComponent = () => (
<form>
<label htmlFor={label}>
{label}
<input
type="text"
id={label}
value={state}
placeholder={label}
onChange={e => setState(e.target.value)}
/>
</label>
</form>
);
return [state, FormComponent, setState];
}
这是使用 Hook 的组件:
function App() {
const [formValue, Form, setFormValue] = useForm("San Francisco, CA", "Location");
return (
<Fragment>
<h1>{formValue}</h1>
<Form />
</Fragment>
);
}