自定义组件打字稿上的ForwardRef

时间:2019-11-13 16:03:57

标签: typescript react-native

我正在尝试使用引用从其父级访问子组件功能。

我有我的父级组件:

const Parent: FC = (props) => {
    let childRef = useRef(null);

    const handle = () => {
        childRef.current.customFunction();
    }

    return (
        <Children props1="value" ref={childRef}/>
        <Button onPress={handle}/>
}

还有我的孩子部分:

interface Props {
    props1: string
}

const Children: FC<Props> = forwardRef((props,ref) => {
    const customFunction = () => {
        console.log("Custom");    
    }

    return <View>props.children</View>
})

呈现子组件时出现打字稿错误:

  

类型'intrinsicAttribute&props&不存在属性'ref'   {children?:ReactNode}

请注意,我想保留任何严格的类型。

2 个答案:

答案 0 :(得分:0)

Call child method from parent

查看此答案。

答案 1 :(得分:0)

您在途中缺少某些类型。

interface Handles {
    customFunction: ()=>void
}
interface Props {
    props1: string
}

const component: RefForwardingComponent<Handles, Props> = (props,ref) => {

    useImperativeHandle(ref, () => ({
        customFunction: () => {
            console.log("Custom");    
        }
    }));

    return <View>props.children</View>
};
const Children = forwardRef(component)


相关问题