0

我的以下代码可能遇到语法问题。随着attrelementRef中代码底部的更新,linting 告诉我:divref

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>
    );
  };
4

1 回答 1

0

您必须给出一个明确useRef的类型,即要引用的 HTML 标记的类型:

const elementRef = React.useRef<HTMLDivElement>(null);

另外,请注意 ref 的唯一有效属性是current检索 ref 的当前值。所以你可能想改变:

elementRef.children

至:

elementRef.current.children

并在您访问 ref 的属性的任何地方进行类似的更改。

于 2020-06-12T23:00:36.253 回答