繁体   English   中英

useRef typescript 'string' 不能用于索引类型'{}'

[英]useRef typescript 'string' can't be used to index type '{}'

我在使用 typescript 和 useRef 时遇到问题:

 <div ref={(el) => (listRef.current[v.name] = el)}>{v.name}</div>

v.name 是一个字符串,它不适用于我的界面:

interface listRefObj {
  [key: string]: string;
}

No index signature with a parameter of type 'string' was found on type '{} | listRefObj'错误。 No index signature with a parameter of type 'string' was found on type '{} | listRefObj'

https://codesandbox.io/s/react-typescript-forked-8fnog1?file=/src/App.tsx

在您的代码中, el可以是HTMLDivElement | null HTMLDivElement | null (而不是string )。 所以正确的注释应该是:

interface listRefObj {
  [key: string]: HTMLDivElement | null;
}

参考类型也需要只是listRefObjuseRef<listRefObj>({})

完整代码

import React, { useRef } from "react";
import "./styles.css";

interface listRefObj {
  [key: string]: HTMLDivElement | null;
}

export default function App() {
  const listRef = useRef<listRefObj>({});

  const result = [
    {
      id: 1,
      name: "apple"
    },
    {
      id: 2,
      name: "orange"
    }
  ];

  return (
    <div className="App">
      {result.map((v) => (
        <div ref={(el) => (listRef.current[v.name] = el)}>{v.name}</div>
      ))}
    </div>
  );
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM