在 React 中将 Ref 作为 Typescript 中的 prop

Kay*_*Kay 1 javascript typescript reactjs

如何将 ref 属性推送到子组件?我收到错误:

'{ reference: RefObject<HTMLSelectElement>; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Property 'reference' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.
Run Code Online (Sandbox Code Playgroud)

我知道它与 React.FC<> 和通用函数有关,但我不知道它是什么类型,我应该在 <> 之间写什么来处理从另一个组件推送的引用。

*编辑:我知道我可以使用forwardRef,但这个问题的重点是如何使用 props 传递 ref。

 const typeRef = useRef<HTMLSelectElement>(null)
    const descriptionRef = useRef<HTMLTextAreaElement>(null)

    const onSubmitHandler = (e: React.FormEvent): void => {
        e.preventDefault()
        
    }

    return (
        <React.Fragment>
            <Navbar />
            <Center width="100%" height="95vh">
                <Flex justifyContent="center" alignItems="center" width="50vw">
                    <FormControl textAlign="center" onSubmit={onSubmitHandler}>
                        <Input ref={titleRef} placeholder="Name for your recipe" />
                        <SelectType reference={typeRef} />
                        <Textarea ref={descriptionRef} placeholder="Description" cols={COLS} rows={ROWS} resize="none" />
                        <Button type="submit">Submit</Button>
                    </FormControl>
                </Flex>
            </Center>
        </React.Fragment>
        
    )
}
Run Code Online (Sandbox Code Playgroud)

孩子:

import { Select } from "@chakra-ui/react"

const SelectType: React.FC<> = (props) => {
    return (
    <Select ref={props.refProp}>
        <option>Breakfast</option>
        <option>Lunch</option>
        <option>Dinner</option>
        <option>Supper</option>
    </Select>
    )
}

export default SelectType
Run Code Online (Sandbox Code Playgroud)

pil*_*ard 8

您只需要为您的组件定义 prop 类型SelectType

const SelectType: React.FC<{ refProp: React.RefObject<HTMLSelectElement> }> = (props) => { ...
Run Code Online (Sandbox Code Playgroud)

TS游乐场