处理Draft.js中列表的选项卡

6

我有一个围绕Draft.js提供的编辑器的包装器,并且我希望能够使UL和OL在按下tab / shift-tab键时正常工作。我定义了以下方法:

  _onChange(editorState) {
    this.setState({editorState});
    if (this.props.onChange) {
      this.props.onChange(
        new CustomEvent('chimpeditor_update',
          {
            detail: stateToHTML(editorState.getCurrentContent())
          })
      );
    }
  }

  _onTab(event) {
    console.log('onTab');
    this._onChange(RichUtils.onTab(event, this.state.editorState, 6));
  }

这里有一个方法叫做_onTab,它与Editor.onTab相连。在这个方法中,我调用了RichUtil.onTab(),我认为它会返回更新后的EditorState,然后我将其传递给一个通用方法来更新EditorState并调用一些回调函数。但是,当我按下tab键或shift+tab键时,什么都没有发生。


这看起来是一个不错的实现,我的机器上运行正常。你看到了console.log输出吗?如果没有,那么你没有正确绑定调用。让我知道文件看起来如何。 - kaushik94
3个回答

4

在使用 React Hooks 进行实现时,我遇到了这个问题,而谷歌搜索结果中的第二个答案解决了我的问题。

我认为 OP 的代码是正确的,但我也遇到了“没有任何反应”的情况。问题最终发现是因为没有包含 Draft.css 样式表。

import 'draft-js/dist/Draft.css'


3
import { Editor, RichUtils, getDefaultKeyBinding } from 'draft-js'


handleEditorChange = editorState => this.setState({ editorState })

handleKeyBindings = e => {
  const { editorState } = this.state
  if (e.keyCode === 9) {
    const newEditorState = RichUtils.onTab(e, editorState, 6 /* maxDepth */)
    if (newEditorState !== editorState) {
       this.handleEditorChange(newEditorState)
    }

    return
  }

  return getDefaultKeyBinding(e)
}

render() {
  return <Editor onTab={this.handleKeyBindings} />
}

3
这似乎没有回答原帖的问题。一个好的答案应该向原帖解释为什么他的代码不能工作,然后给出一个代码示例来进行更改。 - Alonso Dominguez

0
以下示例将把\t注入到当前位置,并相应地更新状态。
function custKeyBindingFn(event) {
if (event.keyCode === 9) {
  let newContentState = Modifier.replaceText(
    editorState.getCurrentContent(),
    editorState.getSelection(),
    '\t'
  );

  setEditorState(EditorState.push(editorState, newContentState, 'insert-characters'));

  event.preventDefault(); // For good measure. (?)
  return null;
}
return getDefaultKeyBinding(event);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接