我很难将下面的React.JS脚本转换为TypeScript。有人能帮忙吗?我正试着在我的网站上放一个导航条。
这是我的Header.tsx文件:
我在onClick={closeMobileMenu}上得到一条红色行-- 'IntrinsicAttributes &{ items: any;}‘类型中不存在属性'onClick’。
<ul className="navbar-nav">
{menuItems.map((menu, index) => {
return (
<MenuItems
items={menu}
key={index}
onClick={closeMobileMenu}
/>
);
})}
</ul>这是我的Menu.tsx文件
我发现了一个错误
上不存在
import React, { useState, useEffect, useRef } from "react";
import {HashLink} from "react-router-hash-link";
import Dropdown from "./Dropdown";
import "./Header.css";
interface MenuItems {
items: string
key: number
onClick: (param: any) => void
}
const MenuItems = ({ items }) => {
let ref = useRef();
const [dropdown, setDropdown] = useState(false);
const onMouseEnter = () => {
window.innerWidth > 960 && setDropdown(true);
};
const onMouseLeave = () => {
window.innerWidth > 960 && setDropdown(false);
};
useEffect(() => {
const handler = (event: { target: any; }) => {
if (dropdown && ref.current && !ref.current.contains(event.target)) {
setDropdown(false);
}
};
document.addEventListener("mousedown", handler);
document.addEventListener("touchstart", handler);
return () => {
// Cleanup the event listener
document.removeEventListener("mousedown", handler);
document.removeEventListener("touchstart", handler);
};
}, [dropdown]);
return (
<li
className="nav-item"
ref={ref}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
onClick={() => setDropdown(false)}
>
{items.submenu ? (
<>
<button
type="button"
aria-haspopup="menu"
aria-expanded={dropdown ? "true" : "false"}
>
<HashLink smooth to={items.path} className="nav-link">
{items.title} <i className="fas fa-chevron-down"></i>
</HashLink>
</button>
<Dropdown submenus={items.submenu} dropdown={dropdown} />
</>
) : (
<HashLink
smooth to={items.path}
className="first-level-nav-link"
>
{items.title}
</HashLink>
)}
</li>
);
};
export default MenuItems;这是我的menuItems.tsx文件:
export const menuItems = [
{
title: "Home",
path: "/",
cName: "nav-link",
submenu: [
{
title: "Story",
path: "/#story",
cName: "nav-link",
},
{
title: "Map",
path: "/#map",
cName: "nav-link",
}
],
},
{
title: "Rewards",
path: "/",
cName: "nav-link",
submenu: [
{
title: "competition",
path: "competition",
cName: "nav-link",
},
{
title: "prizes",
path: "prizes",
cName: "nav-link",
}
],
},
{
title: "Downloads",
path: "downloads",
cName: "nav-link",
}
];发布于 2022-03-08 05:44:05
用于错误#2
如果没有任何额外的信息,TypeScript实际上无法推断您打算如何使用这个引用。
const ref = useRef() // React.MutableRefObject<undefined>但是,useRef可以作为一个泛型来告诉TypeScript您打算如何使用ref。
const ref = useRef<HTMLLIElement>(null) // React.MutableRefObject<HTMLLIElement>只有这样,TypeScript才允许您访问ref.current.contains,因为它知道contains属性存在于HTMLLIElement节点上。
发布于 2022-03-08 05:33:15
更正#1:对于函数引用作为参数,您需要定义任何数据类型
interface MenuItems {
items: any,
key: number,
onClick: any
} 更正#2:在您的MenuItems组件。
const MenuItems = (props: MenuItems ) => {
//access menu item
console.log(props.items.title);
}https://stackoverflow.com/questions/71389653
复制相似问题