首页 > 解决方案 > “字符串”类型的参数不可分配给“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

这是错误

标签: reactjstypescript

解决方案


发生这种情况是因为您将字符串数组中的字符串传递platformschangeSelect,它将类型的事件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>
  );


推荐阅读