简体   繁体   English

为编辑器设置初始 state

[英]Set initial state for editor

I am using lexical and want to set initial text for the editor.我正在使用词法并想为编辑器设置初始文本。

For now, I am just trying to hardcode the initial text.现在,我只是想硬编码初始文本。 Turns out I can't just pass a String.原来我不能只传递一个字符串。

It needs to be in JSON format.它需要采用 JSON 格式。

Thus I am passing in the following instead.因此,我改为传递以下内容。

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

But it throws following error:但它抛出以下错误:

TypeError: Cannot read properties of undefined (reading 'type')类型错误:无法读取未定义的属性(读取“类型”)

What am I doing wrong?我究竟做错了什么?

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>
  );
}

I had the same problem.我有同样的问题。 Apparently editorState can be set to a function:显然 editorState 可以设置为 function:

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

I found this solution in Lexical Playground sources: https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/App.tsx我在 Lexical Playground 来源中找到了这个解决方案: https://github.com/facebook/lexical/blob/main/packages/lexical-playground/src/App.tsx

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

I had this issue too while using a stringified Lexical node tree.我在使用字符串化的词法节点树时也遇到了这个问题。 For context my stringified content came from the Lexical Playground with their "export" feature...对于上下文,我的字符串化内容来自 Lexical Playground 及其“导出”功能......

It wraps what's needed into a {editorState:{...}} .它将需要的内容包装到{editorState:{...}}中。 It seems it's not the standard way for the LexicalComposer to be initialized, so after removing this wrapper to directly get {root:{...}} it works:)似乎这不是初始化LexicalComposer的标准方式,所以在删除这个包装器直接获取{root:{...}}之后它起作用了:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM