简体   繁体   中英

How to use TypeScript and forwardRef in ReactJS?

I'm having a problem when using forwardRef with TypeScript.

What I want? pass a typed ref to the child component.

What am I getting value of console.log - child component null

Code for parent component

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

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

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

Code for child component

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

This is an example to show you how to use forwardRef with typescript

import React, { ChangeEventHandler } from 'react';
import Button from '../button';
import TextInput from '../text-input';
import SearchIcon from '../../icons/Search';

export interface SearchProps {
    className?: string;
    size?: ComponentSize;
    width?: string;
    value?: string;
    onChange?: ChangeEventHandler<HTMLInputElement>;
    placeholder?: string;
}

const Search: React.ForwardRefRenderFunction<HTMLDivElement, SearchProps> = (props, ref) => {
    const { 
        size = 'default',
        className,
        value,
        onChange,
        placeholder,
        width = '100%',
    } = props;


    return (
        <div
            ref={ref}
            className={className}
            width={width}
        >
            <TextInput
                value={value}
                onChange={onChange}
                placeholder={placeholder}
                clearable
            />
            <Button type='secondary' icon={SearchIcon} />
        </div>
    );
}

export default React.forwardRef<HTMLDivElement, SearchProps>(Search);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM