All files / src/codeeditor/_example CodeEditorExample.jsx

41.18% Statements 7/17
0% Branches 0/2
20% Functions 1/5
43.75% Lines 7/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59              1x 1x 1x     1x           1x           1x                   1x                                                
import React, { useState, useCallback, useRef, Fragment } from "react";
import { Row, Col } from "@tencent/tea-component/lib/grid";
import { CodeEditor } from "@tencent/tea-component/lib/codeeditor";
import { LoadingTip } from "@tencent/tea-component/lib/tips";
import { Button } from "@tencent/tea-component/lib/button";
 
export default function CodeEditorExample() {
  const editorRef = useRef(null);
  const [ready, setReady] = useState(false);
  const [editorValue, setEditorValue] = useState("");
 
  // onReady 的时候可以拿到编辑器实例引用,可以用 Ref 保存起来
  const onReady = useCallback(instance => {
    editorRef.current = instance;
    setReady(true);
  }, []);
 
  // onEdit 的时候也可以拿到实例
  const onEdit = useCallback(instance => {
    // getValue() 是个异步方法,返回 Promise
    instance.getValue().then(value => setEditorValue(value));
  }, []);
 
  // 设置编辑器当前内容
  const setExampleCode = useCallback(() => {
    if (editorRef.current) {
      const exampleCode = `console.log('hello <CodeEditor />');`;
      editorRef.current.setValue(exampleCode);
      editorRef.current.updateOptions({ readOnly: true });
      editorRef.current.focus();
      setEditorValue(exampleCode);
    }
  }, []);
 
  return (
    <Fragment>
      <section style={{ border: "1px solid #ddd" }}>
        <Row gap={10}>
          <Col>
            <CodeEditor
              style={{ height: 400 }}
              options={{ language: "javascript" }}
              onReady={onReady}
              onEdit={onEdit}
              autoFocus
            />
          </Col>
          <Col style={{ borderLeft: "1px solid #ddd" }}>
            <pre style={{ height: 400, overflow: "auto" }}>{editorValue}</pre>
          </Col>
        </Row>
      </section>
      <Button disabled={!ready} onClick={setExampleCode}>
        加载示例代码
      </Button>
    </Fragment>
  );
}