React+TypeScript开发富文本编辑器Function类型赋值报错问题咨询
错误原因
- TS类型校验不通过:react-draft-wysiwyg的
Editor组件要求onEditorStateChange属性的类型为(editorState: EditorState) => void,也就是明确接收一个EditorState类型的入参、无返回值的函数,你给onEditorStateChange标注的宽泛Function类型不符合严格的类型匹配要求。 - 额外的不规范写法:你在
MyState中给editorState标注为any、回调函数的入参也标注为any,既浪费了TS的类型校验能力,也容易隐藏类型问题。
修复方案
按以下两个点修改代码即可:
- 将
MyState中editorState的类型从any改为EditorState - 将
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
相关产品推荐
相关产品推荐

