今回は、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は初学者なんで、この記事内に間違い等ありましたらコメントにて指摘してくださると幸いです。
おわり