0

forwardRef使用TypeScript时遇到问题。

我想要的是? 将类型化的 ref 传递给子组件。

我得到 console.log 的价值是什么 -child component null

父组件代码

  // component parent
  import { FormHandles } from '@unform/core';

  export const App = () => {
    const formRef = createRef<FormHandles>();

    return (
      <Child ref={formRef} />
    )
  }

子组件的代码

  // component child
  import { FormHandles } from '@unform/core';

  export const Child = forwardRef<FormHandles>((props, ref) => {
    console.log('child component', ref.current);
    
    return (
      <div>any thing</div>
    )
  })
4

1 回答 1

0
import React, {createRef, forwardRef} from 'react';

type Props = { children: React.ReactNode; type: "submit" | "button" };
type Ref = HTMLButtonElement;

const Child = React.forwardRef<Ref, Props>((props, ref) => {
  console.log(ref);
  return (<button ref={ref} className="MyChild" type={props.type}>{props.children}</button>);
});

function App() {
  const ref = React.createRef<HTMLButtonElement>();
  return (
    <Child type="button" ref={ref}>Click Me</Child>
  )
}

export default App;
于 2021-05-28T14:47:30.250 回答