简体   繁体   English

React TypeScript 无法对表进行排序,因为“类型‘元素’不可分配给类型‘字符串’.ts(2345)”

[英]React TypeScript cant sort a table because of 'Type 'Element' is not assignable to type 'string'.ts(2345)'

I have problem with sorting a table in react component.我在对 React 组件中的表格进行排序时遇到问题。 The issue is related to typescript and it highlights argument and displays an error that is: 'Argument of type '(name1: string, name2: string) => number' is not assignable to parameter of type '(a: Element, b: Element) => number'.该问题与 typescript 相关,它突出显示参数并显示错误:'Argument of type '(name1: string, name2: string) => number' is not assignable to parameter of type '(a: Element, b:元素)=>数字'。 Types of parameters 'name1' and 'a' are incompatible.参数类型“name1”和“a”不兼容。 Type 'Element' is not assignable to type 'string'.类型“元素”不可分配给类型“字符串”。

My parent component:我的父组件:

const SearchWithDropdown: React.FC = () => {
  const [countries, setCountries] = useState<Array<Country>>([])
  const [value, setValue] = useState('')
  const [filteredCountries, setFilteredCountries] = useState<Array<Country>>([])
  const [isVisible, setIsVisible] = useState(false)

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target
    setValue(value)
    changeResultVisibility(value)
  }

  const changeResultVisibility = (value: string) => {
    setIsVisible(value.length >= 3)
  }

  useEffect(() => {
    const fetchMyAPI = async () => {
      let response = await fetch(url)
      const json = await response.json()
      setCountries(json)
    }
    fetchMyAPI()
  }, [])


  useEffect(() => {
    if (value.length >= 3 && countries.length > 0) {
      setFilteredCountries(
        countries
          .filter((el: Country) => el.name.toLowerCase().includes(value))
      )
    }
  }, [value, countries])

  console.log(filteredCountries)

  return (
    <div>
      <input type="text" placeholder="Search..." value={value} onChange={handleChange}></input>
      {isVisible ? (
        filteredCountries.length > 0 ? (
          <DropdownList filteredCountries={filteredCountries} value={value} />
        ) : (
          <div>Not found!</div>
        )
      ) : null}
    </div>
  )
}

And child component:和子组件:

interface DropdownListProps {
  filteredCountries: Country[]
  value: string
}

function sortData (name1: string, name2: string): number {
  name1 = name1.toLowerCase()
  name2 = name2.toLowerCase()
  return name1 > name2 ? 1 : name2 > name1 ? -1 : 0
}

const DropdownList: React.FC<DropdownListProps> = ({ filteredCountries, value }) => {
  const renderData = () =>
    filteredCountries
    .map((el) => (
      <DropdownItem key={el.name}>
        {reactStringReplace(el.name, value, (match: string, i: number) => (
          <strong key={i}>{match}</strong>
        ))}
      </DropdownItem>
    ))
    .sort(sortData)

  return <div>{renderData()}</div>
}

And my d.ts file:还有我的 d.ts 文件:

export interface Country {
  name: string
}

I have tried to solve in by changing declaration in d.ts file, but it sounds a little bit stupid.我试图通过更改 d.ts 文件中的声明来解决,但这听起来有点愚蠢。 I am newbie in TS, so maybe my assumption of sorting in this place is wrong.我是 TS 的新手,所以也许我在这个地方排序的假设是错误的。 Maybe it should be after filter method in parent component... hmm..也许它应该在父组件中的过滤器方法之后......嗯..

Many thanks for a help!非常感谢您的帮助!

It seems that your sort function receives Element , cause you modify your countries array with map method and return array of DropdownItem s.似乎您的排序 function 收到了Element ,因为您使用map方法修改了国家/地区数组并返回了DropdownItem数组。 So I would suggest to do sorting before passing the data to DropdownItem components.所以我建议在将数据传递给 DropdownItem 组件之前进行排序。
Also item of filteredCountries is an object with property name ({name: string}), so your sorting function will receive the object and should extract name property from it filteredCountries的项目也是一个 object 属性名称 ({name: string}),因此您的排序 function 将收到 object 并且应该从中提取名称属性

function sortData (c1: Country, c2: Country): number {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型“null”不可分配给类型“元素”.ts(2345) - Type 'null' is not assignable to type 'Element'.ts(2345) React Router (v6) useNavigate TypeScript 错误:“TS2345:‘number’类型的参数不可分配给‘To’类型的参数” - React Router (v6) useNavigate TypeScript error: "TS2345: Argument of type 'number' is not assignable to parameter of type 'To'" “未定义”类型的参数不可分配给“字符串 |”类型的参数 Blob'.ts(2345) - Argument of type 'undefined' is not assignable to parameter of type 'string | Blob'.ts(2345) 'HTMLElement | 类型的参数 null' 不可分配给'Element' 类型的参数。 类型“null”不可分配给类型“Element”.ts(2345) - Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'Element'.ts(2345) TS2345:“字符串”类型的参数 | undefined&#39; 不能分配给类型为 &#39;string&#39; 的参数。 “未定义”类型不能分配给“字符串”类型 - TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string' 类型“boolean”不可分配给类型“false”.ts(2345) - Type 'boolean' is not assignable to type 'false'.ts(2345) 使用TypeScript 2.0-&gt; TS2345在React中处理多个输入:类型&#39;{[x:string]:string | 布尔; }” - Handing multiple inputs in React with TypeScript 2.0 -> TS2345: Argument of type '{ [x: string]: string | boolean; }' 反应 typescript 错误 - 元素隐式具有任何类型,因为类型字符串的表达式不能用于索引类型 {} - react typescript error - element implicitly has an any type because expression of type string cant be used to index type {} 出现 Typescript 错误:类型“any[]”不可分配给类型“never[]”。 TS2345 - Getting Typescript error: Type 'any[]' is not assignable to type 'never[]'. TS2345 人员类型的 TypeScript 错误 (TS2345) 参数 | undefined 不能分配给 Person 类型的参数 - TypeScript Error (TS2345) argument of type Person | undefined is not assignable to paramater of type Person
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM