繁体   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