LoginSignup
21
19

More than 5 years have passed since last update.

Reactコンポーネント内でjavascript製エディタaceを使う

Last updated at Posted at 2016-02-22

今回は、react-aceというreactでaceを使うための専用ライブラリを紹介します。
リポジトリ:https://github.com/securingsincity/react-ace
今回はes6で書いてます。

使い方

大まかな導入方法はREADME読めば大体分かりますね。npm install react-aceでインストールして、importするだけです。
テーマや言語のシンタックスハイライトは明示的にimportする必要があります。

index.js
import React from 'react';
import brace from 'brace';
import AceEditor from 'react-ace';
import 'brace/mode/ruby';
import 'brace/theme/github';

class Editor extends React.Component{
  render(){
    return(
      <div>
        <AceEditor
          mode="ruby"
          theme="github"
          name="UNIQUE_ID_OF_DIV"
          editorProps={{$blockScrolling: true}}
        />
      </div>
    );
  }
}

ReactDOM.render(
  <Editor />,
  //DOM Element
);

onChangeやonCopyなどの幾つかのaceのイベントハンドラはサポートされていて、普通のReactコンポーネントにonClickを登録するような感覚で使うことができます。

index.js
class Editor extends React.Component{
  handleOnChange(){
    console.log("change!")
  }
  render(){
    return(
      <div>
        <AceEditor
          mode="ruby"
          theme="github"
          name="UNIQUE_ID_OF_DIV"
          editorProps={{$blockScrolling: true}}
          onChange={this.handleOnChange.bind(this)}
        />
      </div>
    );
  }
}

ですがこれだけではちょっともの足りないですね、例えばeditor.insertみたいなメソッドが使えません。そういう時はonLoadを使うらしいです。

index.js
class Editor extends React.Component{
  handleOnChange(){
    console.log("change!")
  }
  handleOnLoad(editor){
    this.editor=editor;
  }
  handleOnClick(){
    this.editor.insert("click!")
  }
  render(){
    return(
      <div>
        <AceEditor
          mode="ruby"
          theme="github"
          name="UNIQUE_ID_OF_DIV"
          editorProps={{$blockScrolling: true}}
          onChange={this.handleOnChange.bind(this)}
          onLoad={this.handleOnLoad.bind(this)}
        />
        <button onClick={this.handleOnClick.bind(this)}>click</button>
      </div>
    );
  }
}

onLoadでthis.editor = editorとしてインスタンスを取得することで、このクラス内ではthis.editorを使うことができるようになります。

僕自身Reactは初学者なんで、この記事内に間違い等ありましたらコメントにて指摘してくださると幸いです。

おわり

21
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
19