[英]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;
}
参考类型也需要只是listRefObj
即useRef<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.