1

这是我为托管 Slate 而创建的 React 组件:

import React, { useMemo, useState } from "react";
import { Field, useField, ErrorMessage } from "formik";
import { Slate, Editable, withReact } from "slate-react";

const FormRichText = ({ label, ...props }) => {
  const [field, meta] = useField(props);
  const editor = useMemo(() => withReact(createEditor()), []);
  const [editorContent, setEditorContent] = useState(field.value);

  field.value = editorContent;

  return (
        <Slate
          {...field}
          {...props}
          name="transcript"
          editor={editor}
          onChange={(v) => setEditorContent(v)}
        >
          <Editable />
        </Slate>
  );
};

export default FormRichText;

我遇到的问题是当我尝试将其连接到 Formik 时,我编辑的任何内容都不会传递给handleSubmit.

<FormRichText
     name="transcript"
     id="transcript"
/>

我不明白 Formik 这就是我遇到问题的原因。我相信我需要显示 Slate 的值(我已将其存储在状态变量中),但我正在努力通过 Formik 了解如何做到这一点。我假设如果我使用userField我可以设置的道具field.value,那将通过 Formik。

4

1 回答 1

1

这有效:

const FormRichText = ({ label, ...props }) => {
  const [field, meta, helpers] = useField(props.name);
  const editor = useMemo(() => withReact(createEditor()), []);

  const { value } = meta;
  const { setValue } = helpers;

  useEffect(() => {
    setValue([
      {
        type: "paragraph",
        children: [{ text: "Type something ..." }],
      },
    ]);
  }, []);

  return (
        <Slate name="transcript" 
          value={value} 
          editor={editor} 
          onChange={(v) => setValue(v)}>
          <Editable />
        </Slate>
      </div>
    </div>
  );
};

希望这对其他人有帮助。

话虽如此,我仍然必须通过 Slate 渲染内容,所以我可能会回到这个线程!

于 2021-08-22T18:10:08.510 回答