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

React+TypeScript开发富文本编辑器Function类型赋值报错问题咨询

错误原因
  • TS类型校验不通过:react-draft-wysiwyg的Editor组件要求onEditorStateChange属性的类型为(editorState: EditorState) => void,也就是明确接收一个EditorState类型的入参、无返回值的函数,你给onEditorStateChange标注的宽泛Function类型不符合严格的类型匹配要求。
  • 额外的不规范写法:你在MyState中给editorState标注为any、回调函数的入参也标注为any,既浪费了TS的类型校验能力,也容易隐藏类型问题。
修复方案

按以下两个点修改代码即可:

  1. 将MyState中editorState的类型从any改为EditorState
  2. 将onEditorStateChange的类型标注从Function改为(editorState: EditorState) => void,同时把入参的any类型改为EditorState
修复后的完整代码
import React, {Component} from 'react';
import { render } from 'react-dom';
import {EditorState} from "draft-js";
import {Editor} from "react-draft-wysiwyg";

type MyProps = {
}

type MyState = {
    editorState: EditorState // 替换any为明确的EditorState类型
}

class EditorContainer extends Component<MyProps,MyState>{
    constructor(props:MyProps){
      super(props);
      this.state = {
        editorState: EditorState.createEmpty(),
      };
    }
  
    // 替换宽泛的Function类型为匹配要求的明确函数类型,入参也替换any为EditorState
    onEditorStateChange: (editorState: EditorState) => void = (editorState: EditorState) => {
      this.setState({
        editorState,
      });
    };
  
    render(){
      const { editorState } = this.state;
      return <div className='editor'>
        <Editor
          editorState={editorState}
          onEditorStateChange={this.onEditorStateChange}    
          toolbar={{
            inline: { inDropdown: true },
            list: { inDropdown: true },
            textAlign: { inDropdown: true },
            link: { inDropdown: true },
            history: { inDropdown: true },
          }}
        />
      </div>
    }
  }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:27:03