我正在处理react钩子表单,我想传递一个富文本编辑器作为输入。我在下面包含了RichText组件,它是一个标准的Draft js实现,但当我单击submit时,我会得到"草稿:未定义的";而不是编辑器中的文本
index.js从"react hook form"导入{useForm,Controller};
const JobPostForm = () => {
const { register, handleSubmit, errors, control } = useForm({
});
return(
<Controller
as={<RichText />}
name="draft"
control={control}
/>
)
}
RichText.js
<Editor
customStyleMap={styleMap}
ref={editor}
editorState={editorState}
onChange={editorState => setEditorState(editorState)}
/>
https://react-hook-form.com/api#Controller
我已经更新了文档,包括js草案示例:
https://codesandbox.io/s/react-hook-form-v6-controller-qsd8r?file=/src/index.js
您应该使用控制器的render
道具
import React from "react";
import { Controller } from "react-hook-form";
import { Editor } from "draft-js";
function RichText({ control }) {
return (
<div
style={{
border: "1px solid #ccc",
minHeight: 30,
padding: 10
}}
>
<Controller
name="DraftJS"
control={control}
render={({ value, onChange }) => (
<Editor editorState={value} onChange={onChange} />
)}
/>
</div>
);
}
export default RichText;
添加到@Bill发布的答案中,我建议使用onEditorStateChange
作为Editor
组件的道具,而不是onChange
。这就是为什么你得到这个错误
TypeError:无法读取未定义的属性"isOnChange";。
这是更新的代码:
import React from "react";
import { Controller } from "react-hook-form";
import { Editor } from "draft-js";
function RichText({ control }) {
return (
<div
style={{
border: "1px solid #ccc",
minHeight: 30,
padding: 10
}}
>
<Controller
name="DraftJS"
control={control}
render={({ value, onChange }) => (
<Editor editorState={value} onEditorStateChange={onChange} />
)}
/>
</div>
);
}
export default RichText;