1

解释起来有点棘手,但我需要生成一个 React 组件,用户可以在其中选择文本并将“标签”应用于文本,这将使文本变为粗体。我需要记录标签的位置,因为这些数据需要存储并在其他需要标签位置的系统中使用。

复杂的部分是用户可以编辑文本并应用重叠标签。

在 DraftJS 中使用实体我创建了一个解决方案,它支持除了重叠标签之外的所有内容,因为在 DraftJS 中,多个实体不能覆盖同一段文本。

    private readonly onTagTypeClicked = (tagType: ITagType) => {
        const editorState = this.state.editorState;
        const selection = this.state.selectionEditorState.getSelection();
        if (!selection.isCollapsed()) {
            const contentState = editorState.getCurrentContent();

            const contentStateWithEntity = contentState.createEntity(
                'TAG',
                'MUTABLE',
                { tag: tagType }
            );

            const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
            const newEditorState = EditorState.set(editorState, { currentContent: contentStateWithEntity });

            this.setState({
                editorState: RichUtils.toggleLink(newEditorState, newEditorState.getSelection(), entityKey)
            });
        }
    }

然后,我尝试使用 contentEditable div 和自定义标签从头开始编写解决方案,但由于 html 生成了格式错误的 html,如下所示

<tag-1 class="tag">This is a <tag-2 class="tag">test</tag-1> of tagging</tag-2>

浏览器会尝试修复这意味着我无法跟踪标签。

我尝试使用注释来解决 html 解析问题:

<!--tag1--><b>This is a</b><!--tag2--><b>test<!--/tag1--> of tagging</b><!--/tag2-->

评论不断消失,阻止了这种方法的工作。

我用 SlateJS 尝试了同样的事情,但结果证明是小故障并且评论不断消失。

public renderMark = (props: any, editor: any, next: any) => {
        switch (props.mark.type) {
            case 'bold':
                return <strong {...props.attributes}> <ReactComment text={'Tag1'} />{props.children} <ReactComment text={'/Tag1'} /> </strong>;
            default:
                return next();
        }
    }

理想情况下,是否有人知道可以处理我正在寻找的现有组件或编写自定义解决方案的强大方法?

4

0 回答 0