我的以下代码可能遇到语法问题。随着attrelementRef
中代码底部的更新,linting 告诉我:div
ref
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>
);
};