如何向 React 功能组件添加方法

Kay*_*ote 0 typescript reactjs react-functional-component

我有一个带有这样的代码的组件:

const Abc: React.FC<AbcTypes> = ({...}) => {...}

Abc.getLayout = () => {...}
Run Code Online (Sandbox Code Playgroud)

我不清楚如何getLayout在 Typescript 中定义/扩展 Abc 组件的方法?

the*_*ude 6

如果您询问如何输入此内容,那么您可以这样做:

const Abc: React.FC<AbcTypes> & { getLayout: () => SomeType } = ({...}) => {...}

Abc.getLayout = () => {...}
Run Code Online (Sandbox Code Playgroud)

如果您正在寻求一种为组件定义命令式 API 的方法,那么useImperativeHandle就是您所寻找的。

这将允许父组件附加引用Abc并调用您定义的方法。

以下是如何使用它的示例:

type AbcRef = {
  getLayout: () => string[]
}
const Abc = forwardRef<AbcRef>((props, ref) => {
  useImperativeHandle(ref, () => ({
    getLayout: () => ['abc'],
  }))

  return <div>Abc</div>
})

const Parent: FC = () => {
  const abcRef = useRef<AbcRef>(null)

  useEffect(() => {
    console.log(abcRef.current?.getLayout())
  }, [])

  return <Abc ref={abcRef} />
}
Run Code Online (Sandbox Code Playgroud)