【问题标题】:Connecting Slate to Formik - is it useField?将 Slate 连接到 Formik - 它是 useField 吗?
【发布时间】:2021-10-23 06:56:26
【问题描述】:

这是我为托管 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 中的 Formik 值。

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

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

【问题讨论】:

    标签: reactjs formik slate


    【解决方案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-12-23
      • 2021-03-11
      • 1970-01-01
      • 2013-08-29
      • 2020-07-20
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      相关资源
      最近更新 更多