reactjs - “字符串”类型的参数不可分配给“ChangeEvent”类型的参数'
问题描述
我刚开始学习打字稿,所以我决定制作一个自定义下拉菜单,但我遇到了这个问题。如何解决这个问题?
import React, { useState } from 'react'
const DropDown = () => {
const platforms = ["Platform_1","Platform_2","Platform_3"]
const [drop, setDrop] = useState<boolean>(false)
const [name, setName] = useState<string | null>('All Platforms')
const changeSelect = (e: React.ChangeEvent<HTMLLIElement>) => {
setName(e.target.textContent)
setDrop(false)
}
return (
<div>
<div className="filter">
<div className="filter-name" onClick={() => setDrop(!drop)}>{name}</div>
{
drop ?
<ul>
{platforms.map((option) =>
<li onClick={e => changeSelect(option)}>{option}</li>
)}
</ul>
:
null
}
</div>
</div>
)
}
export default DropDown
解决方案
发生这种情况是因为您将字符串数组中的字符串传递platforms
给changeSelect
,它将类型的事件React.ChangeEvent<HTMLLIElement>
作为参数而不是字符串。
此外,React.MouseEvent<HTMLLIElement>
如果您打算使用onClick
. 根据您的编辑器,您可能能够找出 React 期望的类型;例如在 VSCode 中,按住Ctrl和悬停onClick
将显示(onClick?: MouseEventHandler<T> | undefined;
在通常的工具提示上方,告诉您应该使用React.MouseEventHandler<T>
htmlT
元素的位置。
这是我对里面代码的修改DropDown
:
const platforms = ["Platform_1", "Platform_2", "Platform_3"];
const [drop, setDrop] = useState<boolean>(false);
const [name, setName] = useState<string | null>("All Platforms");
const changeSelect = (e: React.MouseEvent<HTMLLIElement>) => { //changed type of `e` to React.MouseEvent<HTMLLIElement>
setName(e.currentTarget.textContent); // Changed from e.target to e.currentTarget
setDrop(false);
};
return (
<div>
<div className="filter">
<div className="filter-name" onClick={() => setDrop(!drop)}>
{name}
</div>
{drop ? (
<ul>
{platforms.map((option) => (
<li
onClick={(e: React.MouseEvent<HTMLLIElement>) => { //gave `e` type
changeSelect(e);
}}
>
{option}
</li>
))}
</ul>
) : null}
</div>
</div>
);
推荐阅读
- node.js - 通过 Slack API 上传远程文件
- google-cloud-platform - Google Cloud Run 只能访问 http://metadata.google.internal 上的元数据子集
- android - android应用程序没有显示带有真实ID的广告
- c - 一个八进制转十进制的c程序
- angular - 使用公共参数将 ID 从一个集合拉到另一个集合
- python - 结果合并两个字典列表并更新键
- javascript - jquery如何从数组中删除元素
- html - 是否可以在 Bootstrap 4 中创建一个高度等于其宽度的列?
- java - DateTimeFormatter 个位数月份
- javascript - 如何避免在Javascript中舍入具有超过16位精度的数字