如何使用React.js来使用CKEditor,以允许React识别它? [英] How can CKEditor be used with React.js in a way that allows React to recognize it?
问题描述
我已经尝试使用componentWillMount和componentDidMount从React的上下文中初始化CKEditor,但是不管我尝试什么组合,它似乎都不起作用。有没有人找到一个解决方案,除了切换编辑器?
I've tried using componentWillMount and componentDidMount to initialize CKEditor from within the context of React, but it doesn't seem to work no matter what combination I try. Has anyone found a solution to this besides switching editors?
推荐答案
Sage在他的答案中描述了一个很棒的解决方案。这是一个救生员,因为我刚刚开始使用React,我需要它来实现这一点。但是,我改变了实现,并且还结合了Jared的建议(使用 componentDidMount
)。此外,我的需要是改变回调,如下所示:
Sage describes an awesome solution in his answer. It was a lifesaver, as I've only just started using React, and I needed it to get this going. I did, however, change the implementation, also incorporating Jared's suggestions (using componentDidMount
). Also, my need was to have a change callback, like so:
组件的使用:
<CKEditor value={this.props.value} onChange={this.onChange}/>
将其添加到 index.html
:
<script src="//cdn.ckeditor.com/4.6.1/basic/ckeditor.js"></script>
使用以下组件代码:
import React, {Component} from "react";
export default class CKEditor extends Component {
constructor(props) {
super(props);
this.componentDidMount = this.componentDidMount.bind(this);
}
render() {
return (
<textarea name="editor" cols="100" rows="6" defaultValue={this.props.value}></textarea>
)
}
componentDidMount() {
let configuration = {
toolbar: "Basic"
};
CKEDITOR.replace("editor", configuration);
CKEDITOR.instances.editor.on('change', function () {
let data = CKEDITOR.instances.editor.getData();
this.props.onChange(data);
}.bind(this));
}
}
再次,Sage的所有信用!
Again, all credits to Sage!
以下是上述基本版本的改进版本,它支持同一页面上的多个CKEditor实例:
The following is an improved version of the basic version above, which supports multiple CKEditor instances on the same page:
import React, {Component} from "react";
export default class CKEditor extends Component {
constructor(props) {
super(props);
this.elementName = "editor_" + this.props.id;
this.componentDidMount = this.componentDidMount.bind(this);
}
render() {
return (
<textarea name={this.elementName} defaultValue={this.props.value}></textarea>
)
}
componentDidMount() {
let configuration = {
toolbar: "Basic"
};
CKEDITOR.replace(this.elementName, configuration);
CKEDITOR.instances[this.elementName].on("change", function () {
let data = CKEDITOR.instances[this.elementName].getData();
this.props.onChange(data);
}.bind(this));
}
}
请注意,这需要一些唯一的ID被传递还有:
Please note that this requires some unique ID to be passed along as well:
<CKEditor id={...} value={this.props.value} onChange={this.onChange}/>
这篇关于如何使用React.js来使用CKEditor,以允许React识别它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!