11

伙计们!请帮忙。

我想要什么:从新行开始时,用户键入一个 URL 并按下Enter我想删除包含该 URL 的块并将其替换为自定义Entity. 很像文档中的媒体示例,但没有Add image按钮。

我尝试了什么:(只是一个粗略的草稿)

var mediaBlockRenderer = function(block) {
    if (block.getType() === 'atomic') {
        return {
            component: TestComponent,
            editable: false
        };
    }
    return null;
};

var TestComponent = function() {
    return <div className="test-component">TEST COMPONENT</div>;
};

onChange: function(editorState) {
        var currentKey = editorState.getSelection().getStartKey();
        var content = editorState.getCurrentContent();
        var selection = content.getSelectionBefore();
        var beforeKey = content.getKeyBefore(currentKey);
        var block = content.getBlockForKey(beforeKey);

        if (block && block.getText() === 'test') {
            console.log(block.getText());
            var len = block.getCharacterList().size;

            var newSelection = selection.merge({
                anchorOffset: 0,
                focusOffset: len
            });

            var newContent = Modifier.removeRange(content, newSelection, 'backward');
            editorState = EditorState.push(editorState, newContent, 'insert');
            var key = Entity.create('media', 'IMMUTABLE');
            editorState = AtomicBlockUtils.insertAtomicBlock(
                editorState,
                key,
                ' '
            );
            //editorState = EditorState.forceSelection(editorState, newContent.getSelectionBefore());

        }

        this.setState({
            editorState: editorState
        })
    }

它几乎做了我想要的,但是按退格键不能删除插入的块,光标只是跳到右上角。

我的问题:替换块的推荐方法是什么?你如何删除一个块?为什么我插入的块不会被删除?

谢谢!

4

1 回答 1

1

我最终通过使用Modifier.replaceText而不是Modifier.removeRange. 您可以做的是找到 URL 的初始索引和 URL 的最后索引(让我们分别称它们为ab),我们可以执行以下操作:

let newSelection = editorState.getSelection();
newSelection = newSelection.merge({
    anchorOffset: a,
    focusOffset: b
});

let newContent = Modifier.replaceText(editorState.getCurrentContent(), newSelection, "");
let newState = EditorState.push(editorState, newContent, 'insert-characters');

this.setState({ editorState: newState });

您还可以定义您newSelection想要的任何方式,因此如果您更喜欢分区,ContentBlocks则可以。

于 2020-06-04T18:37:45.863 回答