我想将 CodeMirror 编辑器用作使用
react-hook-form
的表单中的字段。有没有人以前做过这个以及如何使用react hook form register
方法注册编辑器值?
您可以使用
Controller
中的 react-hook-form
组件来包装 CodeMirror
组件。 Controller
组件旨在与不受控制的组件配合使用,例如 CodeMirror
,它们不会公开 onChange
事件。您可以使用 Controller
处理 CodeMirror
和 react-hook-form
之间的事件和更新。
像这样-
import { useForm, Controller } from "react-hook-form";
import { UnControlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
function YourComponent() {
const { handleSubmit, control } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="code"
control={control}
defaultValue=""
render={({ field }) => (
<CodeMirror
{...field}
options={{
lineNumbers: true
}}
onChange={(editor, data, value) => {
field.onChange(value);
}}
/>
)}
/>
<input type="submit" />
</form>
);
}
基本上,
Controller
包装了CodeMirror
组件,并且onChange
的CodeMirror
属性用于在编辑器中的代码更改时更新表单值。