gpt4 book ai didi

reactjs - ACE 编辑器的薄包装,用于制作 React 组件

转载 作者:行者123 更新时间:2023-12-04 16:45:56 25 4
gpt4 key购买 nike

我编写了一个组件,它是 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 , 只做了很少的小改动。

我做错了吗?

最佳答案

你会想挂接 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

关于reactjs - ACE 编辑器的薄包装,用于制作 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34088073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com