Draft js 在 return 键上添加新块
Draft js add new block on return key
我一直在尝试在 return 键上添加一个新块。这是我的代码,它被放置在一个用于检查 keyCode
的开关盒中。 shift + return 通过添加新行来工作。但是只是return,它需要在编辑器中开始一个新块。
// SHIFT + RETURN <br/>
if(e.shiftKey) {
const newEditorState = RichUtils.insertSoftNewline(this.state.editorState);
if (newEditorState !== this.state.editorState) {
this.onChange(newEditorState);
}
} else {
const newBlock = new ContentBlock({
key: genKey(),
type: "unstyled",
text: ""
});
const contentState = this.state.editorState.getCurrentContent();
const newBlockMap = contentState.getBlockMap().set(newBlock.getKey(), newBlock);
EditorState.push(
this.state.editorState,
ContentState
.createFromBlockArray(newBlockMap.toArray(), contentState.getBlockMap())
.set("selectionAfter", contentState.getSelectionAfter().merge({
anchorKey: newBlock.getKey(),
anchorOffset: 0,
focusKey: newBlock.getKey(),
focusOffset: 0,
isBackward: false
})),
"split-block"
);
}
控制台没有错误。当按下 return 键时,它什么都不做。
希望有人能提供帮助。
我设法让它工作于:
// SHIFT + RETURN <br/>
if(e.shiftKey) {
const newEditorState = RichUtils.insertSoftNewline(this.state.editorState);
if (newEditorState !== this.state.editorState) {
this.onChange(newEditorState);
}
} else {
const editorState = this.state.editorState;
const currentContent = editorState.getCurrentContent();
const selection = editorState.getSelection();
const textWithEntity = Modifier.splitBlock(currentContent, selection);
this.setState({
editorState: EditorState.push(editorState, textWithEntity, "split-block")
});
}
希望对下一个人有帮助!
我一直在尝试在 return 键上添加一个新块。这是我的代码,它被放置在一个用于检查 keyCode
的开关盒中。 shift + return 通过添加新行来工作。但是只是return,它需要在编辑器中开始一个新块。
// SHIFT + RETURN <br/>
if(e.shiftKey) {
const newEditorState = RichUtils.insertSoftNewline(this.state.editorState);
if (newEditorState !== this.state.editorState) {
this.onChange(newEditorState);
}
} else {
const newBlock = new ContentBlock({
key: genKey(),
type: "unstyled",
text: ""
});
const contentState = this.state.editorState.getCurrentContent();
const newBlockMap = contentState.getBlockMap().set(newBlock.getKey(), newBlock);
EditorState.push(
this.state.editorState,
ContentState
.createFromBlockArray(newBlockMap.toArray(), contentState.getBlockMap())
.set("selectionAfter", contentState.getSelectionAfter().merge({
anchorKey: newBlock.getKey(),
anchorOffset: 0,
focusKey: newBlock.getKey(),
focusOffset: 0,
isBackward: false
})),
"split-block"
);
}
控制台没有错误。当按下 return 键时,它什么都不做。
希望有人能提供帮助。
我设法让它工作于:
// SHIFT + RETURN <br/>
if(e.shiftKey) {
const newEditorState = RichUtils.insertSoftNewline(this.state.editorState);
if (newEditorState !== this.state.editorState) {
this.onChange(newEditorState);
}
} else {
const editorState = this.state.editorState;
const currentContent = editorState.getCurrentContent();
const selection = editorState.getSelection();
const textWithEntity = Modifier.splitBlock(currentContent, selection);
this.setState({
editorState: EditorState.push(editorState, textWithEntity, "split-block")
});
}
希望对下一个人有帮助!