我想在编辑器的onChange中使用event.stopPropagation()
。
class MyEditor extends Component {
constructor(props) {
super(props);
this.onChange = (editorState) => {
// Is there a way to get event here?
};
}
render() {
// ...
return (
<Editor editorState={editorState} onChange={this.onChange} />
);
}
}
有办法获取事件吗?谢谢
更新:添加我的案例。我有一个编辑器,它从 IndexedDB 中保存的 Redux 加载数据。由于在 convertToRaw
和 convertFromRaw
之后选择(光标)将会丢失,因此我使用 localEditorState 来维护光标。
编辑器有一个包装器。如果用户单击编辑器包装器,我想将光标移动到末尾。如果用户单击内部编辑器,我希望光标使用 localEditorState 中的选择信息。
class Send extends PureComponent {
constructor(props) {
super(props);
this.state = {
localEditorState: EditorState.createEmpty(),
shouldMoveCursorToEnd: false
};
// ...
}
componentDidMount() {
const { loadEditor } = this.props;
loadEditorFromIndexedDB();
}
onEditorWrapperClick() {
const { editorState } = this.props;
this.domEditor.focus();
this.setState({ shouldMoveCursorToEnd: true });
}
onEditorChange(newEditorState) {
// Without event.stopPropagation(), onEditorWrapperClick will also run, which is not what I want
this.setState({ shouldMoveCursorToEnd: false });
this.updateEditorText(newEditorState);
}
updateEditorText(newEditorState) {
const { updateEditor } = this.props;
this.setState({ localEditorState: newEditorState });
updateEditor(newEditorState);
this.saveToIndexedDB({ newEditorState });
}
render() {
const { editorState } = this.props;
const { localEditorState, shouldMoveCursorToEnd } = this.state;
const editorStateWithSelection = shouldMoveCursorToEnd
? EditorState.moveFocusToEnd(editorState)
: EditorState.acceptSelection(editorState, localEditorState.getSelection());
return (
<form onClick={this.onEditorWrapperClick}>
<Editor editorState={editorStateWithSelection} onChange={this.onEditorChange} />
<button type="submit">Send</button>
</form>
);
}
}
export default Send;
最佳答案
我有一种感觉,您正在寻找的解决方案将涉及操纵 onMouseDown()
您的合成事件<Editor/>
组件至preventDefault()
/stopPropagation()
并相应地执行自定义逻辑。
点击<Wrapper/>
内的任何其他地方组件应设置编辑器状态以将插入符号放在编辑器的末尾。
您生成的实现可能类似于以下内容:
// Component.
<form onMouseDown={this.handleWrapperClick}>
<Editor .. onMouseDown={this.handleEditorClick}/>
</form>
// Logic.
handleWrapperClick = (event) => {
// Manipulate editorState to focus / place caret at end of <Editor/>.
}
handleEditorClick = (event) => {
// Intercept / Cancel Click Event.
event.preventDefault()
event.stopPropagation()
// Set editorState to match selection info from localEditorState.
}
关于javascript - 如何获取Draft.js中Editor的onChange事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47006792/