一个ACE编辑器的瘦包装器,用于制作React组件

时间:2015-12-04 12:08:24

标签: reactjs ace-editor

我写了一个组件,它是ace编辑器的瘦包装器。 ACE编辑器只会出现一秒然后消失,这很奇怪。

完整代码如下:

import React, { PropTypes, Component } from 'react';

class AceEditor extends Component {

  static propTypes = {
    mode: PropTypes.string.isRequired,
    content: PropTypes.string.isRequired,
  };

  static defaultProps = {
    mode: 'javascript',
    code: '//write your code here',
  };

  render() {
      const jsCode = '<div id="my-ace-editor" style="font-size: 14px !important;border: 1px solid lightgray;">' +
        this.props.code + '</div> \
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.2/ace.js" type="text/javascript" charset="utf-8"></script> \
      <script> \
        var editor = ace.edit("my-ace-editor"); \
        editor.setTheme("ace/theme/clouds"); \
        editor.getSession().setMode("ace/mode/javascript"); \
        editor.setShowPrintMargin(false); \
        editor.setOptions({minLines: 25}); \
        editor.setOptions({maxLines: 50}); \
      </script>';

      return <div id="ace-editor-container" dangerouslySetInnerHTML={{__html: jsCode}} />
    //return <p>{this.props.code}</p>
  }
}

export default AceEditor;

这个想法很简单,只需使用dangerouslySetInnerHTML插入原始HTML代码,原始HTML代码如下:

<div id="ace-editor-container">
<div id="my-ace-editor" style="font-size: 14px !important;border: 1px solid lightgray;">function foo(items) {
    var x = "All this is syntax highlighted";
    return x;
}</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.2/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
    var editor = ace.edit("my-ace-editor");
    editor.setTheme("ace/theme/clouds");
    editor.getSession().setMode("ace/mode/javascript");
    editor.setShowPrintMargin(false);
    editor.setOptions({minLines: 25});
    editor.setOptions({maxLines: 50});
</script>
</div>

原始HTML代码来自官方网站https://ace.c9.io/#nav=embedding,只有很少的修改。

我做错了吗?

1 个答案:

答案 0 :(得分:7)

您想要挂钩componentDidMount以将React与许多其他库联系起来:

import React, { PropTypes, Component } from 'react';

class AceEditor extends Component {

  static propTypes = {
    mode: PropTypes.string,
    content: PropTypes.string,
  };

  static defaultProps = {
    mode: 'javascript',
    code: '//write your code here',
  };

  componentDidMount(){
    const node = React.findDOMNode(this.refs.root);
    const editor = ace.edit(node);
    editor.setTheme("ace/theme/clouds");
    editor.getSession().setMode("ace/mode/javascript");
    editor.setShowPrintMargin(false);
    editor.setOptions({minLines: 25});
    editor.setOptions({maxLines: 50});
  }

  render() {
    const style = {fontSize: '14px !important', border: '1px solid lightgray'};
      return (
        <div ref="root" style={style}>
          {this.props.code}
        </div>
      );
  }
}

export default AceEditor;

在开发版本的其他地方包含ace.js,或者如果库支持,则使用CommonJS模块。

工作示例:http://codepen.io/romseguy/pen/LGYxNj