1

我真的是打字稿世界的初学者,我目前使用的 React Table 库在文档中默认没有类型。

所以,我想请你帮忙将类型添加到IndeterminateCheckbox 方法

const IndeterminateCheckbox = React.forwardRef(
  ({ indeterminate, ...rest }, ref) => {
    const defaultRef = React.useRef()
    const resolvedRef = ref || defaultRef

    React.useEffect(() => {
      resolvedRef.current.indeterminate = indeterminate
    }, [resolvedRef, indeterminate])

    return (
      <>
        <input type="checkbox" ref={resolvedRef} {...rest} />
      </>
    )
  }
)

这是来自 React Table 文档的沙盒链接: https ://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/row-selection-and-pagination?from-embed=&file=/ src/App.js:613-1010

我的第二个问题是:我在哪里可以找到类型并自己添加它们?

4

1 回答 1

0

1. 创建@types/react.d.ts

/* eslint-disable */

declare namespace React {
  export default interface RefObject<T> {
    current: T | null;
  }
}

2.输入组件

/* eslint-disable no-param-reassign */

import React, { forwardRef, useEffect, useRef } from 'react';

interface IIndeterminateInputProps {
  indeterminate?: boolean;
  name: string;
}

const useCombinedRefs = (
  ...refs: Array<React.Ref<HTMLInputElement> | React.MutableRefObject<null>>
): React.MutableRefObject<HTMLInputElement | null> => {
  const targetRef = useRef(null);

  useEffect(() => {
    refs.forEach(
      (ref: React.Ref<HTMLInputElement> | React.MutableRefObject<null>) => {
        if (!ref) return;

        if (typeof ref === 'function') {
          ref(targetRef.current);
        } else {
          ref.current = targetRef.current;
        }
      },
    );
  }, [refs]);

  return targetRef;
};

const IndeterminateCheckbox = forwardRef<
  HTMLInputElement,
  IIndeterminateInputProps
>(({ indeterminate, ...rest }, ref: React.Ref<HTMLInputElement>) => {
  const defaultRef = useRef(null);
  const combinedRef = useCombinedRefs(ref, defaultRef);

  useEffect(() => {
    if (combinedRef?.current) {
      combinedRef.current.indeterminate = indeterminate ?? false;
    }
  }, [combinedRef, indeterminate]);

  return (
    <>
      <input type="checkbox" ref={combinedRef} {...rest} />
    </>
  );
});

export default IndeterminateCheckbox;


于 2021-02-03T20:00:03.220 回答