我正在尝试修饰一些文本,但它应该是ajax调用的结果,以指定要修饰的文本部分,而不是使用正则表达式策略来管理进程。可以使用修饰符库中的任何方法吗?我的想法是在onChange方法内部调用一些东西并修改editorstate。任何想法都将不胜感激。
发布于 2018-08-04 03:49:14
我的解决方案使用了一个自定义装饰器和一个动态正则表达式,这种组合可能有助于实现您所希望的效果。
代码结构遵循this示例来装饰draftjs中的tweet。
您可以使用ajax调用替换代码中的字符串数组(var arr = "one","two","three")。
import React, { Component } from 'react';
import { Editor, EditorState, CompositeDecorator } from 'draft-js';
const styles = {
handle: {
color: 'black',
backgroundColor: '#FF7F7F',
direction: 'ltr',
unicodeBidi: 'bidi-override',
},
};
// arr can be accessed from an ajax call
var arr = ["one", "two", "three"]
const HANDLE_REGEX = new RegExp("(?:[\\s]|^)(" + arr.join("|") + ")(?=[\\s]|$)", 'gi')
function handleStrategy(contentBlock, callback, contentState) {
findWithRegex(HANDLE_REGEX, contentBlock, callback);
}
function findWithRegex(regex, contentBlock, callback) {
const text = contentBlock.getText();
let matchArr, start;
while ((matchArr = regex.exec(text)) !== null) {
start = matchArr.index;
callback(start, start + matchArr[0].length);
}
}
const HandleSpan = (props) => {
return (
<span
style={styles.handle}
data-offset-key={props.offsetKey}
>
{props.children}
</span>
);
};
class App extends Component {
constructor(props) {
super(props);
const compositeDecorator = new CompositeDecorator([
{
strategy: handleStrategy,
component: HandleSpan,
}
]);
this.state = {
editorState: EditorState.createEmpty(compositeDecorator),
};
this.onChange = (editorState) => this.setState({editorState});
}
render() {
return (
<div className="container-root">
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
placeholder="Write..."
ref="editor"
spellCheck={true}
/>
</div>
);
}
}
export default App;
https://stackoverflow.com/questions/51195426
复制相似问题