【问题标题】:How to use Ref in a component that is forwarding its ref in React Native如何在 React Native 中转发其 ref 的组件中使用 Ref
【发布时间】:2021-07-17 16:51:52
【问题描述】:

我有一个 react 本机自定义输入组件,并且我成功地将其 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>
   );
});

【问题讨论】:

    标签: javascript react-native react-native-component


    【解决方案1】:

    Travis Waith-Mair 的这篇文章展示了您想用示例做什么:https://non-traditional.dev/how-to-use-the-forwarded-ref-in-react-1fb108f4e6af


    编辑:

    似乎链接文章的作者 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>
       );
    });
    
    

    【讨论】:

    • 这对我有用。我的问题很难表达和理解,但我很高兴你准确地抓住了它
    猜你喜欢
    • 2020-01-25
    • 2019-08-06
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多