【问题标题】:ForwardRef on a custom component typescript自定义组件打字稿上的 ForwardRef
【发布时间】:2019-11-13 16:03:57
【问题描述】:

我正在尝试使用引用从他的父级访问子组件函数。

我有我的父组件:

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}

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

【问题讨论】:

    标签: typescript react-native


    【解决方案1】:

    您在途中遗漏了一些类型。

    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)
    
    
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2018-03-04
      • 2021-01-15
      • 1970-01-01
      • 2018-10-20
      • 2017-01-22
      • 1970-01-01
      • 2020-06-02
      • 2017-02-20
      相关资源
      最近更新 更多