react-hook-form Controller with react-draft-wysiwyg

react-hook-form Controller with react-draft-wysiwyg

我需要一些帮助。我在我的项目中使用了 react-final-form,但我决定更改为 react-hook-form。顺便说一下,我喜欢它,但我被卡住了。 :/

在我的页面上,我正在使用编辑器从用户那里收集一些信息。目前我正在使用 react-draft-wysiwyg。 这里的代码:

parentComponent.js

/**
 * react-hook-form library
*/
const {
    register,
    handleSubmit,
    control
} = useForm({
    mode: 'onChange'
});

<form onSubmit={handleSubmit(onSubmit)}>
    <Controller
        as={<WYSIWYGEditor />}
        name='editor'
        control={control}
        onChange={([ event ]) => event.target.value}
    />
</form>

WYSIWYGEditor.js

const WYSIWYGEditor = ({ input }) => {
    const [ editorState, setEditorState ] = useState(EditorState.createEmpty());
    const onEditorStateChange = editorState => {
        setEditorState(editorState);
    };

    return (
        <React.Fragment>
            <div className={classes.root}>
                <Editor
                    editorState={editorState}
                    wrapperClassName='wrapper-class'
                    editorClassName='editor-class'
                    onEditorStateChange={onEditorStateChange}
                />
            </div>
        </React.Fragment>
    );
};

export default WYSIWYGEditor;

请注意: input prop 来自 react-final-form 的编码。输入正在传递我正在输入的字符。因此,如果我将 input 作为道具,它会失败,因为它不存在。 React-hook-form 不传递输入。 我用 props:

改变了它
const WYSIWYGEditor = props=> {
    console.log(props)

当我输入任何内容时,我在 console.log 中得到以下内容:

{name: "editor", value: undefined, onChange: ƒ}

如您所见,值为 undefined。我如何构造 Controller 以便每次在编辑器中键入内容时传递一个值?

感谢您的帮助

我找到了解决办法。

value 未定义,因为显然在组件加载时没有要加载的内容。如果您不想看到 undefined,只需从控制器传递 defaultValue=''

<Controller
  as={<WYSIWYGEditor />}
  name='editor'
  control={control}
  onChange={([ event ]) => event.target.value}
  defaultValue='' <== here
/>

现在,不允许 return 任何类型值的问题是因为我已经从控制器声明了 onChange。所以,正确的代码是:

<Controller
  as={<WYSIWYGEditor />}
  name='editor'
  control={control}
  defaultValue=''
/>

此外,在 WYSIWYGEditor.js 文件中,您需要将之前的 input 替换为 props。原因是它们传递的是完全相同的对象,其中包含 valueonChangeonBlur 函数。

这是一个带有工作代码的代码沙箱: https://codesandbox.io/s/trusting-mountain-k24ys?file=/src/App.js