react-富文本编辑框遇到的问题

项目需求实现一个划词功能,由于textarea的局限性,考虑到使用div来实现,通过设置div的contentEditable来模拟文本框。实现代码如下:

class ContentEditable extends Component {
  constructor(props) {
    super(props)
  }

  shouldComponentUpdate(nextProps) {
    return nextProps.html !== this.elem['innerText']
  }

  onChange = (e) => {
    const value   = this.elem['innerText']
    this.props.onChange(e, value)
  }

  render() {
    const { html, contentEditable, ...props } = this.props
    return (
      <div
        {...props}
        ref={(elem) => { this.elem = elem }}
        dangerouslySetInnerHTML={{ __html: html }}
        contentEditable={contentEditable}
        onInput={ this.onChange }
      />
    )
  }
}

e.g.
<ContentEditable
     html={this.state.value}
     className="editable-sample-selection"
     contentEditable={isPatternCheckSuccess}
     onChange={this.handleEditTextChange}
 />
...
handleEditTextChange = (e, value) => {
    this.setState({
      title: value
    })
  }

重点注意该方法

shouldComponentUpdate(nextProps) {
return nextProps.html !== this.elem['innerText']
}
通过shouldComponentUpdate控制组件的渲染,从而解决不用每次输入都重新渲染组件,导致光标回位到初始状态的问题。

需要普及的关于dangerouslySetInnerHTML需要了解的
https://www.cnblogs.com/daowangzhizhu-pt/p/6385088.html
关于contentEditable属性可参看张鑫旭大神的两篇文章
http://www.zhangxinxu.com/wordpress/2016/01/contenteditable-plaintext-only/
http://www.zhangxinxu.com/wordpress/2010/12/div-textarea-height-auto/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原教程内容详见精益 React 学习指南,这只是我在学习过程中的一些阅读笔记,个人觉得该教程讲解深入浅出,比目前大...
    leonaxiong阅读 7,830评论 1 18
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 6,143评论 0 2
  • 说在前面 关于 react 的总结过去半年就一直碎碎念着要搞起来,各(wo)种(tai)原(lan)因(le)。心...
    陈嘻嘻啊阅读 11,804评论 7 41
  • 深入JSX date:20170412笔记原文其实JSX是React.createElement(componen...
    gaoer1938阅读 12,459评论 2 35
  • 以下内容是我在学习和研究React时,对React的特性、重点和注意事项的提取、精练和总结,可以做为React特性...
    科研者阅读 12,563评论 2 21