1

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

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

父组件.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>

所见即所得Editor.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;

请注意: 输入道具来自带有 react-final-form 的编码。输入正在传递我正在输入的字符。所以,如果我input作为道具离开,它会失败,因为它不存在。React-hook-form 不传递输入。我已经改变了props

const WYSIWYGEditor = props=> {
    console.log(props)

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

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

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

谢谢你的帮助

4

1 回答 1

2

我找到了解决方案。

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

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

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

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

此外,在WYSIWYGEditor.js文件中,您需要将之前的内容替换inputprops. 原因是它们传递的对象完全相同,其中包含一个value、、onChangeonBlur函数。

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

于 2020-06-08T08:43:32.417 回答