在 draft.js 编辑器中,我自定义代码以在键入“*”后将文本样式设置为粗体

问题描述 投票:0回答:0
        if(text.length > 1)
          subString = text.substring(text.length-2, text.length);
        if(subString == "* ")
        {
          toggleInlineStyle("BOLD");
          text = `${text.slice(0, text.length-2)}`;
          console.log(text);

          const contentState  = editorState.getCurrentContent();
          const selectionState  = editorState.getSelection();
          const lastTwoChars = contentState.getBlockForKey(selectionState.getAnchorKey())
                            .getText()
                            .slice(-1);

          const newContentState = Modifier.replaceText(
            contentState,
            selectionState.merge({ 
              anchorOffset: selectionState.getFocusOffset() - 1,
              focusOffset: selectionState.getFocusOffset(), }),
            '',
          );
          
          // Create a new EditorState with the new ContentState and selection
          const newEditorState = EditorState.push(
            editorState,
            newContentState,
            'remove-range'
          )
          let updatedEditorState = EditorState.forceSelection(
              newEditorState, 
              newContentState.getSelectionAfter()
            );

          // Set the new EditorState as the current state of the editor
          updatedEditorState = RichUtils.toggleInlineStyle(editorState, "BOLD");
         const newState2 = RichUtils.toggleBlockType(updatedEditorState, "header-one");
          setEditorState(newState2);

        }

这是我目前在项目中所做的,通过在第一行输入“*”来设置文本样式。 风格是完美的,但有一些问题,“*”没有消失。

删除最后两个字母(“*”)有效但粗体样式在编辑器上不起作用。

          const lastTwoChars = contentState.getBlockForKey(selectionState.getAnchorKey())
                            .getText()
                            .slice(-1);

          const newContentState = Modifier.replaceText(
            contentState,
            selectionState.merge({ 
              anchorOffset: selectionState.getFocusOffset() - 1,
              focusOffset: selectionState.getFocusOffset(), }),
            '',
          );
          
          // Create a new EditorState with the new ContentState and selection
          const newEditorState = EditorState.push(
            editorState,
            newContentState,
            'remove-range'
          )
          let updatedEditorState = EditorState.forceSelection(
              newEditorState, 
              newContentState.getSelectionAfter()
            );

javascript reactjs typescript string draftjs
© www.soinside.com 2019 - 2024. All rights reserved.