【问题标题】:Draftjs apply inline styling to text programaticallyDraft Js 以编程方式将内联样式应用于文本
【发布时间】:2017-10-07 20:32:29
【问题描述】:

我有以下功能

 buttonToSelection(){
  const editorState = this.state.editorState;
  var selectionState = editorState.getSelection();
  const newSelection = selectionState.merge({
        anchorOffset: 1,
        focusOffset: 10
  })
  const newEditorState = EditorState.forceSelection(editorState, newSelection);
  this.editorChangeState(RichUtils.toggleInlineStyle(newEditorState,'STRIKEOUT'));
}

我想要实现的是单击按钮样式,文本范围在 1 到 10 之间并带有 STRIKEOUT。该功能目前执行此操作,但也保留文本的选择。我只是想让它改变文本的样式。

【问题讨论】:

    标签: draftjs


    【解决方案1】:

    你做的几乎是正确的。但是,由于您为 Draft 提供了一个新选择(适合使用 RichUtils 添加样式),它会尝试呈现该选择。因此,在调用editorChangeState 之前,您必须再次将选择重置为之前的值。下面是它的外观(带有一些过度描述的变量):

    buttonToSelection = () => {
      const editorState = this.state.editorState;
      const selectionState = editorState.getSelection();
      const newSelection = selectionState.merge({
        anchorOffset: 1,
        focusOffset: 10
      })
      const editorStateWithNewSelection = EditorState.forceSelection(editorState, newSelection);
      const editorStateWithStyles = RichUtils.toggleInlineStyle(editorStateWithNewSelection,'STRIKEOUT')
      const editorStateWithStylesAndPreviousSelection = EditorState.forceSelection(
        editorStateWithStyles,
        selectionState
      )
      this.editorChangeState(editorStateWithStylesAndPreviousSelection);
    }
    

    Here's a fiddle 正在展示它。在点击按钮之前,请确保您在编辑器中至少写了 11 个字符,否则它会中断。

    【讨论】:

      猜你喜欢
      • 2019-02-23
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      相关资源
      最近更新 更多