簡體   English   中英

如何在 React Native 中轉發其 ref 的組件中使用 Ref

[英]How to use Ref in a component that is forwarding its ref in React Native

我有一個 react native 自定義輸入組件,我成功地將它的 ref 轉發給了一個父組件。 現在,我也想參考孩子本身的輸入,我該怎么做??

 //my imports here //my text field component export const MyTextField = React.forwardRef((props, ref) => { const [inputValue, setValue] = useState(''); const clearInput = () => { setValue(""); //I want to get the input by ref here and apply "clear()" method on it } return ( <View> <TextInput /* How can i also use this ref to refer to this textinput in The "clearInput" function above */ ref={ref} value={inputValue} onChangeText={(value) => setValue(value)} {...props} /> <IconButton icon="close-circle" onPress={clearInput} /> </View> ); });

Travis Waith-Mair這篇文章展示了您想用示例做什么: https : Travis Waith-Mair


編輯:

似乎鏈接文章的作者 Travis 也創建了相關代碼段的 npm 包:https ://www.npmjs.com/package/@bedrock-layout/use-forwarded-ref


這是一個帶有示例的小吃: https : //snack.expo.io/@truetiem/use-forwardedref

如果你想在你的代碼中實現它:

// Copy-Pasted the "useForwardedRef" from the linked article by "Travis Waith-Mair"
const useForwardedRef = (ref) =>{
   const innerRef = useRef(null);

   useEffect(() => {
     if (!ref) return;
     if (typeof ref === 'function') {
       ref(innerRef.current);
     } else {
       ref.current = innerRef.current;
     }
   });
 
   return innerRef;
}

export const MyTextField = React.forwardRef((props, ref) => {
   const forwardedRef = useForwardedRef(ref);
   const [inputValue, setValue] = useState('');

   const clearInput = () => {
      setValue("");
      
      // We can now access the ref with forwardedRef
      forwardedRef.current?.clean?.();
   }


   return (
      <View>
         <TextInput
            // We are passing the forwardedRef here
            ref={forwardedRef}
            value={inputValue}
            onChangeText={(value) => setValue(value)}
            {...props}
         />
         <IconButton
            icon="close-circle"
            onPress={clearInput}
         />
      </View>
   );
});

暫無
暫無

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

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