家伙!请帮助。
我想要的内容:从新行开始,用户键入URL并按Enter
,我想删除包含URL的块并将其替换为自定义的Entity
。与文档中的Media示例非常相似,但没有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的最后索引(让我们分别称为a
和b
),然后可以执行以下操作:
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
进行分区,则可以。