【问题标题】:Set initial state for editor设置编辑器的初始状态
【发布时间】:2023-01-27 19:04:45
【问题描述】:

我正在使用 lexical 并想为编辑器设置初始文本。

现在,我只是想硬编码初始文本。原来我不能只传递一个字符串。

它需要是 JSON 格式。

因此,我改为传递以下内容。

'{"text":"sample text"}'

但它抛出以下错误:

类型错误:无法读取未定义的属性(读取“类型”)

我究竟做错了什么?

function Placeholder() {
  return <div className="editor-placeholder">Enter some rich text...</div>;
}

const editorConfig = {

  // This is how I am trying to set initial value.
  // no errors if I remove this. I need this cos I need to set initial value.
  editorState: '{"text":"sample text"}',

  // other params
};

export default function Editor() {

  return (
    <LexicalComposer initialConfig={editorConfig}>
      <div className="editor-container">
        <ToolbarPlugin />
        <div className="editor-inner">
          <RichTextPlugin
            contentEditable={<ContentEditable className="editor-input" />}
            placeholder={<Placeholder />}
          />
          {/* other login components */}
        </div>
      </div>
    </LexicalComposer>
  );
}

【问题讨论】:

    标签: javascript next.js lexicaljs


    【解决方案1】:

    我有同样的问题。显然 editorState 可以设置为一个函数:

    const editorConfig = {
      editorState: () => {
        const root = $getRoot();
        root.clear();
        const p = $createParagraphNode();
        p.append($createTextNode("preloaded node"));
        root.append(p);
      }
    };
    

    我在 Lexical Playground 资源中找到了这个解决方案:https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/App.tsx

    这是一个简化的例子:https://codesandbox.io/s/lexical-plain-playground-72pwge?file=/src/Editor.js:683-960

    【讨论】:

      【解决方案2】:

      我在使用字符串化的词法节点树时也遇到了这个问题。对于上下文,我的字符串化内容来自 Lexical Playground 及其“导出”功能......

      它将需要的内容包装成{editorState:{...}}。似乎这不是初始化 LexicalComposer 的标准方式,所以在删除此包装器直接获取 {root:{...}} 后它可以工作:)

      【讨论】:

        猜你喜欢
        • 2021-11-05
        • 1970-01-01
        • 1970-01-01
        • 2020-11-02
        • 1970-01-01
        • 2021-10-01
        • 2021-03-10
        • 2018-06-10
        • 1970-01-01
        相关资源
        最近更新 更多