You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-summernote@2.0.2设置默认值后onChange事件失效问题求助

解决react-summernote@2.0.2设置默认值后onChange不触发的问题

你遇到的问题确实是因为通过jQuery直接调用summernote('code')修改内容后,react-summernote组件内部的状态监听被干扰,导致自带的onChange无法正常触发。可以用以下两种方法解决:

方法一:手动绑定summernote原生change事件

放弃组件自带的onChange,在onInit里直接绑定summernote的原生summernote.change事件,同步内容到React状态:

<ReactSummernote
  className="ReactSummernote"
  codeview={this.state.codeview}
  options={{
    height: 350,
    dialogsInBody: true,
    toolbar: [
      ["style", ["style"]],
      ["font", ["bold", "underline", "clear"]],
      ["fontname", ["fontname"]],
      ["para", ["ul", "ol", "paragraph"]],
      ["table", ["table"]],
      ["insert", ["link", "picture", "video"]],
      ["view", ["codeview"]]
    ]
  }}
  onInit={() => {
    const $editor = $('.ReactSummernote');
    // 设置默认内容
    $editor.summernote('code', this.state.email_body);
    // 绑定原生change事件同步状态
    $editor.on('summernote.change', (_, contents) => {
      console.log("text changed");
      this.setState({ email_body: contents });
    });
  }}
/>

别忘了在组件卸载时解绑事件,避免内存泄漏:

componentWillUnmount() {
  $('.ReactSummernote').off('summernote.change');
}

方法二:尝试用组件的defaultValue属性初始化(如果适用)

虽然你提到value/children无效,但可以试试defaultValue属性,这是react-summernote部分版本支持的初始化方式,避免直接操作DOM:

<ReactSummernote
  className="ReactSummernote"
  codeview={this.state.codeview}
  defaultValue={this.state.email_body}
  options={{
    height: 350,
    dialogsInBody: true,
    toolbar: [
      ["style", ["style"]],
      ["font", ["bold", "underline", "clear"]],
      ["fontname", ["fontname"]],
      ["para", ["ul", "ol", "paragraph"]],
      ["table", ["table"]],
      ["insert", ["link", "picture", "video"]],
      ["view", ["codeview"]]
    ]
  }}
  onChange={(email_body) => {
    console.log("text changed");
    this.setState({email_body});
  }}
/>

如果defaultValue也无效,方法一的手动绑定是最可靠的方案,直接绕开组件内部的监听冲突,用原生事件同步状态。

内容的提问来源于stack exchange,提问作者user20071254

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 13:35:56