【问题标题】:How to Decorate a text with Modifier in Draft.js如何在 Draft.js 中使用修饰符装饰文本
【发布时间】:2018-07-05 15:45:54
【问题描述】:

我正在尝试装饰一些文本,但不是让进程由正则表达式策略管理,它应该是 ajax 调用的结果,以指定要装饰的文本和平。是否可以使用修改器库中的任何方法?我的想法是在 onChange 方法中调用一些东西并修改 editorstate。 任何想法将不胜感激。

【问题讨论】:

    标签: draftjs draft-js-plugins


    【解决方案1】:

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

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

    您可以将代码中的字符串数组(var arr = ["one", "two", "three"])替换为 ajax 调用。

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      相关资源
      最近更新 更多