gpt4 book ai didi

javascript - React Draft-js block 插入

转载 作者:行者123 更新时间:2023-12-03 14:30:46 34 4
gpt4 key购买 nike

工作原理:当用户点击空格键时,将查询 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
});

block 渲染图:

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

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

自定义 block 组件:

// 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;

问题:当用户点击空格键时,就会出现此功能。文本被换行,并且正确的 block 被添加到 DOM 中。我遇到以下两个困难:

  • 我需要在文本末尾插入一个空格。
  • 光标跳回到文档的开头,但也停留在通过元素创建的新 block 内。我需要它在新 block 之外和文本末尾恢复编辑。

我已经在网上搜索过,但到目前为止还没有运气,感谢任何帮助。

谢谢!

最佳答案

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

   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
});

关于javascript - React Draft-js block 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368369/

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