簡體   English   中英

如何使用 TypeScript 在 React Native 中將 forwardRef 與 FunctionComponent 一起使用

[英]How to use forwardRef with FunctionComponent in React Native using TypeScript

我已經查看了許多文檔和示例,但我似乎仍然不太明白如何在 React Native 中使用帶有 TypeScript 的功能組件的forwardRef 下面是我使用自定義函數創建MyCustomComponent的示例,我嘗試通過創建引用從父級調用該函數。 但是,由於 ref 定義不正確且為null ,我顯然收到一條錯誤消息,告訴我該函數不存在。 請幫助我了解如何在 React Native 中正確使用forwardRef 提前致謝!

interface MyCustomComponentProps {
  title: string
}

const MyCustomComponent: React.FunctionComponent<MyCustomComponentProps> = React.forwardRef((props, ref) => {
  const coolAlert = () => {
    Alert.alert('Hey!', 'This was called from MyCustomComponent')
  }
  return (
    <View>
      <Text>{props.title}</Text>
    </View>
  )
})

export default function App () {
  const MyCustomComponentRef = useRef()
  return (
    <SafeAreaView>
      <MyCustomComponent ref={MyCustomComponentRef} title='Hello World' />
      <TouchableOpacity
        onPress={() => {
          MyCustomComponentRef.coolAlert()
        }}>
        <Text>Click Me</Text>
      </TouchableOpacity>
    </SafeAreaView>
  )
}

轉發參考

Refs 可能真的很令人困惑,因為有多種方法可以處理它們,而且人們不知道 ref 對象( React.MutableRefObjectReact.RefObject )和 ref 值之間的區別,該值存儲在.current屬性中引用對象。 你在這里犯了那個錯誤,以及一些丟失或不正確的打字稿類型。

useRef<T>是一個通用鈎子,其中值T表明將存儲什么類型的值。 我們需要告訴App我們打算用一個coolAlert方法存儲一些東西。 實際上我們稍后會看到我們需要我們的 ref 是不可變的,所以我們將使用createRef<T>代替。

interface MyRef {
  coolAlert(): void;
}

const MyCustomComponentRef = createRef<MyRef>();

當我們調用onPress ,我們需要訪問 ref 對象的當前值。 通過將泛型添加到createRef ,打字稿已經知道這個值是MyRefundefined 我們可以使用可選的鏈接?.調用coolAlert ?. 操作員。

onPress={() => MyCustomComponentRef.current?.coolAlert()}

現在我們需要對MyCustomComponent做一些工作。 你錯誤地為它分配了React.FunctionComponent<MyCustomComponentProps>類型,因為函數組件沒有我們需要的關於 ref 轉發的知識。

function forwardRef<T, P = {}>(Component: RefForwardingComponent<T, P>): ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<T>>;

MyCustomComponent的類型應該是forwardRef復雜返回類型。 但是我們不需要自己分配那個類型,我們只需要將泛型TP傳遞給forwardRef函數調用。 T是 ref 的類型, P是 props 的類型。

const MyCustomComponent = React.forwardRef<MyRef, MyCustomComponentProps>(...

好的,我們擺脫了所有打字稿錯誤 好極了! 除了……等等。 它實際上沒有做任何事情 所有這一切,它仍然不起作用。 我討厭裁判。 參考是壞的。

使用參考

我們將 ref 轉發給MyCustomComponent ,后者現在可以訪問轉發的 ref 並可以將其附加到 DOM 組件。 但是我們不希望它附加到 DOM 元素,我們希望它附加到MyCustomComponent 但我們真的不能那樣做。

默認情況下,您不能在函數組件上使用 ref 屬性,因為它們沒有實例[docs]

我們必須使用一個叫做useImperativeHandle的鈎子,感覺就像一個黑客解決方案,甚至文檔說“不要這樣做”。 是的,我討厭裁判。

useImperativeHandle 自定義在使用 ref 時暴露給父組件的實例值。 與往常一樣,在大多數情況下應該避免使用 refs 的命令式代碼。 useImperativeHandle 應該與 forwardRef 一起使用。 [文檔]

我們必須通過useImperativeHandle公開我們的coolAlert方法。

useImperativeHandle(ref , () => ({coolAlert}));

現在它真的有效了,終於!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM