【问题标题】:Text selection bug with draft.js and decoratorDraft.js 和装饰器的文本选择错误
【发布时间】:2019-02-15 20:38:57
【问题描述】:

我正在使用 Draft.js 编辑器,因此我需要更新装饰器以及它在 onChange 中动态呈现的组件的道具。这用背景颜色标记部分文本。

我几乎可以完成这项工作,但有一个奇怪的错误,除其他外,无法在装饰组件之一之后立即选择角色。

这是一个重现错误的最小(人工)示例:

import React from 'react';
import { CompositeDecorator, Editor, EditorState } from 'draft-js';


const Marked = ({ children, background }) => <span style={{ background }}>{children}</span>;


class TestEditor extends React.Component {
  constructor(props) {
    super(props);

    this.state = { editorState: EditorState.createEmpty() };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(editorState) {
    const markers = [{ from: 3, to: 7 }, { from: 12, to: 15 }];

    const strategy = (contentBlock, callback) => {
      const text = contentBlock.getText();
      markers.forEach(({ from, to }) => {
        if (text.length >= to) callback(from, to);
      });
    };

    const decorator = new CompositeDecorator([
      { strategy, component: (props) => <Marked {...props} background="#00ff2a1a" /> },
    ]);

    const newEditorState = EditorState.set(editorState, { decorator });

    this.setState({ editorState: newEditorState });
  }

  render() {
    const { editorState } = this.state;

    return <Editor editorState={editorState} onChange={this.handleChange} />;
  }
}

export default TestEditor;

这将是一个文本输入,其中位置 3 - 7 和 12 - 15 的文本具有绿色背景(如果存在)。

如果我现在写aaabbbbccc,则不可能选择第一个c。使用鼠标选择它,直到我释放鼠标按钮;使用键盘时,它似乎根本没有被选中(可能是暂时的)。

如果我在handleChange 方法中使用没有新输入的静态组件,它可以正常工作:const decorator = new CompositeDecorator([{ strategy, component: Marked }]);。但是,这不适合我的用例。

有什么建议吗?

【问题讨论】:

  • 很少能做'on the fly'

标签: javascript draftjs


【解决方案1】:

最后结果证明我可以用草稿的entities 做我需要的事情,而且性能可能要好得多

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多