React Draft-js 块插入

React Draft-js Block Insert

工作原理: 当用户点击 space 栏时,将查询 Draft-JS 文本内容以查找特定单词。然后,该词的所有实例都包含在标签中。文本换行后,HTML 被转换回来,Draft-JS 编辑器状态被更新:

      const convertedFromHTML= convertFromHTML(newHTML);
      const editorState = this.state.editorState;

      // Set Editor and Content States
      const newContentState = ContentState.createFromBlockArray(
        convertedFromHTML.contentBlocks,
        convertedFromHTML.entityMap
      );

      const nextEditorState = EditorState.push(
        editorState,
        newContentState,
        'insert-text'
      );

      this.setState({ 
        editorState: nextEditorState
      });

块渲染图:

const blockRenderMap = Immutable.Map({
  'Atomic': {
    element: 'Atomic' ,
    wrapper: <GoogleCustomBlock />
  }
});

const myBlockStyleFn = (contentBlock) => {
   const type = contentBlock.getType();
   switch (type) {
     case 'atomic': {
      return 'GoogleCustomBlock';
   }
}

自定义块组件:

// React Components
import React, { Component } from 'react';

class GoogleCustomBlock extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div className='GoogleCustomBlock'>
        {this.props.children}
      </div>
    );
  }
}

导出默认的 GoogleCustomBlock;

问题: 当用户点击 space 栏时会出现此功能。文本被换行,正确的块被添加到 DOM。我有以下两个困难:

我已经在网上搜索过,但到目前为止还没有找到任何帮助,我们将不胜感激。

谢谢!

解决方案: 突出显示文本并在 space-bar 键盘命令上插入 space:

   insertInlineStyles = (editorState, indexes, googleSearchTerm) => {
      const contentState = editorState.getCurrentContent()
      const selectionState = editorState.getSelection();

      // Loop Through indexes //
      const newSelection = selectionState.merge({
        anchorOffset: index[i],
        focusOffset: googleSearchTerm.length
      })

      // Create new Editor State with Selection on Targeted Word //
      const editorStateWithNewSelection = EditorState.forceSelection(editorState, newSelection);

      // Toggle Inline Style //
      const editorStateWithStyles = RichUtils.toggleInlineStyle(editorStateWithNewSelection,'GoogleStyle');

      // Set Selection Back to Previous //
      const editorStateWithStylesAndPreviousSelection = EditorState.forceSelection(
        editorStateWithStyles,
        selectionState
      )

      // Return Editor //
      return editorStateWithStylesAndPreviousSelection;
   }

    /// INSIDE OF ANOTHER FUNCTION

    /// GET INDEX OF WORD TO HIGHLIGHT
    var indexes = [INDEX OF WORD];

    /// INSERT INLINE STYLES
    var newEditorState = this.insertInlineStyles(this.state.editorState, indexes, googleSearchTerm);

    /// ADD SPACE to TEXT
    let newContentState = Modifier.replaceText(
      newEditorState.getCurrentContent(), // New content
      currentState.getSelection(), // End of old content selection
      " " // Text to add
    );
    let finalEditorState = EditorState.push(
      newEditorState, 
      newContentState, 
      'insert-characters'
    );

    this.setState({ 
      editorState: finalEditorState 
    });