![](/img/trans.png)
[英]Typescript error on React Component: Argument of type 'Element' is not assignable to parameter of type
[英]Handling Ref in React Functional Component written in TypeScript: Element is not assignable error
我的以下代码可能遇到语法问题。 elementRef
在带有ref
attr 的div
中的代码底部更新,linting 告诉我:
let elementRef: React.MutableRefObject<null>
Type 'HTMLDivElement | null' is not assignable to type 'MutableRefObject<null>'.
Type 'null' is not assignable to type 'MutableRefObject<null>'.ts(2322)
我显然不了解 createRef 的工作原理,并希望得到一些指导。
FC代码:
interface VerticalNavExpansionPanelInterface {
location: any;
item: any;
key: any;
children: any;
}
const VerticalNavExpansionPanel: React.FC<VerticalNavExpansionPanelInterface> = ({ location, item, key, children }) => {
const [collapsed, toggleCollapsed] = React.useState(true)
let history = useHistory();
//let elementRef = React.createRef();
let elementRef = React.useRef(null);
let componentHeight = 0;
const handleClick = () => {
toggleCollapsed(!collapsed);
};
const calcaulateHeight = (node: any) => {
if (node.name !== "child") {
for (let child of node.children) {
calcaulateHeight(child);
}
}
componentHeight += node.clientHeight;
return;
};
React.useEffect(() => {
calcaulateHeight(elementRef);
// // OPEN DROPDOWN IF CHILD IS ACTIVE
for (let child of elementRef.children) {
if (child.getAttribute("href") === location.pathname) {
toggleCollapsed(false);
}
}
});
return (
<div>
<TouchRipple
className="nav-item flex-middle h-48 w-100"
onClick={() => handleClick()}
>
<div>
<Icon className="text-middle item-icon">{item.icon}</Icon>
<span className="text-middle pl-20 item-text">{item.name}</span>
</div>
{item.badge && (
<div className={`badge bg-${item.badge.color}`}>{item.badge.value}</div>
)}
<div
className={
collapsed
? classes.collapseIcon + " item-arrow"
: classes.expandIcon + " item-arrow"
}
>
<Icon className="text-middle">chevron_right</Icon>
</div>
</TouchRipple>
<div
ref={(el) => (elementRef = el)}
className={"submenu"}
style={
collapsed
? { maxHeight: "0px" }
: { maxHeight: componentHeight + "px" }
}
>
{children}
</div>
</div>
);
};
您必须为useRef
提供一个显式类型,该类型是想要引用的 HTML 标记的类型:
const elementRef = React.useRef<HTMLDivElement>(null);
另外,请注意 ref 的唯一有效属性是current
,它检索 ref 的当前值。 所以你可能想改变:
elementRef.children
至:
elementRef.current.children
并在您访问 ref 的属性的任何地方进行类似的更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.