如何在Draft.js中使用修饰符装饰文本

时间:2018-07-05 15:45:54

标签: draftjs draft-js-plugins

我正在尝试装饰一些文本,但是与其通过正则表达式策略来管理该过程,不应该是ajax调用的结果,以指定要装饰哪种文本。可以使用Modifier库中的任何方法吗?我的想法是在onChange方法中调用某些内容并修改editorstate。 任何想法将不胜感激。

1 个答案:

答案 0 :(得分:1)

我的解决方案使用自定义装饰器和动态正则表达式,这种组合可能有助于实现您希望的效果。

代码结构遵循this示例,以装饰draftjs中的推文。

enter image description here

您可以使用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;
相关问题