簡體   English   中英

如何在ReactJS中使用TypeScript和forwardRef?

[英]How to use TypeScript and forwardRef in ReactJS?

我在將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>
    )
  })
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;

這是一個示例,向您展示如何將 forwardRef 與 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM