关于react-ace初始化自动折叠代码记录

696 阅读1分钟

前言

最近折腾react-ace这个库,发现自动折叠功能是官方不支持初始化直接字段配置的,就到处找issue。 自己研究出了一种初始化支持自动折叠的方式。

直接上代码

    import AceEditor from 'react-ace';
    import 'ace-builds/src-noconflict/mode-json';
    import 'ace-builds/src-noconflict/theme-kuroir';
    import 'ace-builds/src-noconflict/ext-language_tools';
    
    const aceRef = useRef<any>(null);
    
    // 关键这个折叠方法
    useEffect(() => {
    if (aceRef.current) {
      aceRef?.current.editor.session.foldAll(
        1,
        aceRef?.current.editor.session.doc.getAllLines().length,
      );
    }
  }, [aceRef.current]);
    
    <AceEditor
      placeholder="Placeholder Text"
      mode="json"
      theme="kuroir"
      name="json"
      height="400px"
      width="100%"
      fontSize={10}
      ref={aceRef}
      showPrintMargin={false}
      maxLines={1000}
      highlightActiveLine={true}
      wrapEnabled
      editorProps={{ $blockScrolling: true }}
      value={json}
      setOptions={{
        enableBasicAutocompletion: false,
        enableLiveAutocompletion: false,
        enableSnippets: false,
        showLineNumbers: true,
        tabSize: 2,
        useWorker: false,
        wrap: true,
      }}
    />

记录一下,希望对后面用的人有用处。over!