draft.js:让光标显示在最后面

focus的时候,光标在最前面,如何把光标移到最后面
if(document.activeElement.contentEditable != 'true') { // #1
    const editorState = moveSelectionToEnd(this.state.editorState) //#2
    this.setState({ editorState },()=>{ //#3
        this.domEditor.focus() 
    })            
}

#1 activeElement.contentEditable

粗略的判断:contentEditable就代表是draft.js的编辑器
这么做是为了避免重复focus,不然每次点击编辑框,光标都会跑到最后面

#2 moveSelectionToEnd

封装好的函数,直接拿着用就好了,代码在后面

#3 回调函数

一定要用setState的回调函数,确保在editorState更新之后再focus,
不然不会成功

不要使用redux来管理editorState

setState的回调函数可以确保执行顺序: 先更新,再执行
而redux不能保证更新与执行的先后顺序
比如,

...
dispatch(action) // 改变了store中的editorState,进而导致react重新渲染
domEditor.focus() // 无法确定这行代码 是在react组件更新完成之前还是之后执行
...

最后,moveSelectionToEnd.js

import {  EditorState, SelectionState } from 'draft-js';
const moveSelectionToEnd = (editorState) => {
  const content = editorState.getCurrentContent();
  const blockMap = content.getBlockMap();
  const key = blockMap.last().getKey();
  const length = blockMap.last().getLength();
  const selection = new SelectionState({
      anchorKey: key,
      anchorOffset: length,
      focusKey: key,
      focusOffset: length,
  });
  return EditorState.acceptSelection(editorState, selection);
};
export default moveSelectionToEnd;

猜你喜欢

转载自blog.csdn.net/sinat_24070543/article/details/80384433