gpt4 book ai didi

draftjs - 替换内容 block

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

伙计们!请帮忙。

我要的是:从新行开始时,用户键入 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
})
}

它几乎完成了我想要的,但是无法通过按退格键删除插入的块,光标只是跳到右上角。

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

谢谢!

最佳答案

我最终通过使用 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 进行分区你可以。

关于draftjs - 替换内容 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37254105/

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