简体   繁体   English

添加类型以在 React 中使用 TypeScript 从父级向子级传递 ref state 设置器

[英]Add types for passing a ref state setter from parent to child with TypeScript in React

I lost some hours and don't get this.我失去了几个小时,没有得到这个。 I tried a ton of examples, but nothing worked.我尝试了很多例子,但没有任何效果。 How do I solve these sort of challenges?我该如何解决这些挑战? How do I know what kind of types Typescript wants for those things, and why the hell should ANYONE do such things with typescript, since in JS it just works!我怎么知道 Typescript 想要什么样的类型来处理这些事情,以及为什么任何人都应该用 typescript 做这样的事情,因为在 JS 中它只是工作!

I just want to pass my useState from parent to the child, and there I want to set a Ref of a div to the useState so that the parent can manipulate the div (and its children).我只想将我的 useState 从父级传递给子级,并且我想将 div 的 Ref 设置为 useState,以便父级可以操纵 div(及其子级)。

const Parent: React.FC<iParent> = ({title}) => {
    
    const x = React.useRef() as React.MutableRefObject<HTMLDivElement>;;
    const refSetter = useState(x);

  return(
       <Child setMyRef={refSetter} />
  )

}



interface iChild {
  setMyRef: Dispatch<SetStateAction<React.MutableRefObject<HTMLDivElement>>>;
}
const Child: React.FC<iChild> = ({setMyRef}) => {
  
  const myRef = useRef(???type?);
  
  useEffect(() => {
    if(myRef.current){
        setMyRef(myRef);
    }
  }, [])

  return(
       <div ref={myRef} />
  )

}

You can do it as below.您可以按如下方式进行。 And yeah TypeScript can be verbose but it worth it and you get used to it quickly.是的,TypeScript 可能很冗长,但值得,你很快就会习惯。 A way to know what type for what variable is to read the error you get and also what you see when you hover over a one.一种了解什么变量类型的方法是读取您得到的错误以及您在 hover 超过一个时看到的内容。

import {Dispatch, FC, RefObject, SetStateAction, useEffect, useRef, useState } from "react";

interface iChild {
  setMyRef: Dispatch<SetStateAction<RefObject<HTMLDivElement> | null>>;
}
const Child: FC<iChild> = ({ setMyRef }) => {
  const myRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setMyRef(myRef);
  }, [setMyRef]);

  return <div ref={myRef} />;
};

const Parent: FC<iParent> = ({ title }) => {
  const [ref, refSetter] = useState<RefObject<HTMLDivElement> | null>(null);

  return <Child setMyRef={refSetter} />;
};

在 CodeSanbox 上编辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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