reactjs - 将 React useMemo() 与 TypeScript 一起使用时,不能分配给类型 '() => void' 错误?
问题描述
我有一个非常简单的带有打字稿的反应应用程序。
import React, { useState, useMemo } from "react";
import { Editor as Draft, EditorState } from "draft-js";
const Editor: React.FC = () => {
const [editorState, setEditorState] = useState<() => EditorState>(() =>
EditorState.createEmpty()
);
const handleEditorChange = useMemo(
(nextEditorState: EditorState) => setEditorState(nextEditorState),
[editorState]
);
return (
<div>
<Draft editorState={editorState} onChange={handleEditorChange} />
</div>
);
};
export default Editor;
我正在尝试使用它,useMemo()
但是当我换行时handleEditorChange
,useMemo
我收到以下错误:
argument of type '(nextEditorState: EditorState) => void' is not assignable to parameter of type '() => void'
如何在这里正确使用 TypeScript 并摆脱错误?
解决方案
useMemo用于记忆提供给它的函数的返回值,但您将它用作 onChange 处理程序。
所以删除它并只使用该函数作为处理程序
const handleEditorChange = (nextEditorState: EditorState) =>
setEditorState(nextEditorState)
其次,您将状态键入为返回EditorState
不正确的函数,您希望类型为EditorState
.
TypeScript 还可以推断类型,因此您甚至不需要键入它
const [editorState, setEditorState] = useState(EditorState.createEmpty())
推荐阅读
- firebase-realtime-database - Firebase 实时数据库的安全规则中的级联
- docker - 为什么 docker 对奇点构建强制执行拉取率限制?
- ruby-on-rails - 无法将应用程序部署到heroku
- testing - 渲染器进程占用过多内存柏树时 Docker 崩溃?
- c++ - Mbed 错误的 long int 解析
- delphi - IOS部署错误【PAClient错误】错误:E0776
- node.js - 在 NodeJS“readline”模块中获取用户的输入
- python - “i for i”有什么作用,它是如何工作的?除了在列表中建立索引之外,它是否有用?
- ms-access - 仅在一台 PC 上的特殊下拉响应
- vue.js - Nuxt.js 常用 SCSS 模块?