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

TypeScript自定义Dropdown报错:string类型不可赋值给ChangeEvent<HTMLLIElement>参数

报错原因

你定义的changeSelect函数要求接收React.ChangeEvent<HTMLLIElement>类型的事件对象,但实际调用时传入的是platforms遍历出来的字符串类型的option,二者类型不匹配触发了TS类型校验报错。另外补充:ChangeEvent仅适用于input、select等表单值变更事件,li的点击事件属于MouseEvent,本身就不匹配ChangeEvent类型定义。

修复方案

方案1(更推荐,逻辑更直接)

直接修改changeSelect函数参数为接收选中的字符串值,不需要通过事件对象拿文本内容,逻辑更可控没有边界问题:

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')

    // 修改参数类型为string
    const changeSelect = (selectedOption: string) => {
        setName(selectedOption)
        setDrop(false)
    }

    return (
        <div>
            <div className="filter">
                <div className="filter-name" onClick={() => setDrop(!drop)}>{name}</div>
                {drop ? 
                <ul>
                    {platforms.map((option) => 
                    // 直接传option字符串即可
                    <li onClick={() => changeSelect(option)}>{option}</li>
                    )}
                </ul> 
                : null}
            </div>
        </div>
    )
}

export default DropDown

方案2(保留事件对象写法)

如果需要使用事件对象,需要修正事件类型定义,同时调用时传入事件对象而非字符串:

import React, { useState, MouseEvent } 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')

    // 修改事件类型为li的点击事件类型
    const changeSelect = (e: MouseEvent<HTMLLIElement>) => {
        // 处理textContent可能为null的边界情况
        setName(e.target.textContent ?? 'All Platforms')
        setDrop(false)
    }

    return (
        <div>
            <div className="filter">
                <div className="filter-name" onClick={() => setDrop(!drop)}>{name}</div>
                {drop ? 
                <ul>
                    {platforms.map((option) => 
                    // 调用时传入事件对象e
                    <li onClick={(e) => changeSelect(e)}>{option}</li>
                    )}
                </ul> 
                : null}
            </div>
        </div>
    )
}

export default DropDown

内容的提问来源于stack exchange,提问作者Moran Low

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:48:03