javascript - Draft.js 's RichUtils.toggleInlineStyle doesn' 工作

标签 javascript jquery reactjs semantic-ui draftjs

Draft.js 的 RichUtils.toggleInlineStyle 无法正常工作。请帮忙! 我的代码在 JSfiddle .

有什么误解吗?

var TextArea = React.createClass({
  ...
  toggleBlockStyle: function(blockType) {
    this.onChange(RichUtils.toggleBlockType(this.state.editorState, blockType)); // don't work!
  },

  toggleInlineStyle: function(inlineStyle) {
    this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, inlineStyle)); // don't work!
  },

  handleClear: function() {
    this.onChange(EditorState.push(this.state.editorState, 
        ContentState.createFromText(''), 'remove-range')); // don't work!
  },
  ...
  render: function() {
    return (
      <div onClick={this.onFocus}>
        {this.renderButtons()}
        <Editor editorState={this.state.editorState}
          className={this.props.className}
          name={this.props.name} ref="editor"
          placeholder={this.props.placeholder}
          handleKeyCommand={this.handleKeyCommand}
          onChange={this.onChange}
          spellCheck={true}
          stripPastedStyles={true}
          customStyleMap={myStyleMap}/>
      </div>);
   }
}

最佳答案

当您使用按钮切换样式时,会导致编辑器失去焦点并且不会应用样式。使用在编辑器取消焦点之前触发的 onMouseDown 而不是 onClick

我在 github 线程中发现了此修复 here 。为方便起见,引用:

However, using onClick causes the text area to go out of focus and the style isn't toggled. I did some digging and found other solutions that suggested using preventDefault on the onClick function, but that doesn't do anything. With this event handler, the style is toggled only if the text is highlighted first and doesn't allow for the text to be styled prior to typing. I saw another solution that suggested replacing onClick with onMouseDown as it doesn't cause the text area to lose focus. I tried this, and it worked. I also delved into the source code for Draft.js, and in the demo editor code I saw this code:

 //...
  render() {
//...
    return (
      <span className={className} onMouseDown={this.onToggle}>
        {this.props.label}
      </span>
    );
  }
}; 

关于javascript - Draft.js 's RichUtils.toggleInlineStyle doesn' 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37161497/

相关文章:

javascript - JQuery:如何选择表格行,但不选择单元格内表格的行

reactjs - 如何在 MUI v5 中将图标添加到 Mobile DatePicker

javascript - 动态 Highcharts 渲染不起作用

javascript - jquery 验证

javascript - RateIt jquery 插件与我项目中的 jquery 文件发生冲突?

javascript - 在 React 中渲染动态输入字段

javascript - HTML Javascript - 用搜索字段替换按钮 onclick

javascript - ng-repeat 中的 Angular 多复选框数组

javascript - 通过 REST API 在 BlockBlob 上设置 Azure 元数据

javascript - 使用复选框过滤数据表并保持刷新状态