【问题标题】:Send ref via props in functional component通过功能组件中的 props 发送 ref
【发布时间】:2021-10-08 20:06:44
【问题描述】:

在我的父组件中,我调用钩子 useRef:const flatListRef = useRef(null); ,然后我想在子组件中使用这个 flatListRef。我试图在documentation 中这样做,但没有成功。当我调用我的函数 toTop 我得到:null is not an object (evaluating 'flatListRef.current.scrollToOffset')

这是我的父组件:

const BeautifulPlacesCards = ({navigation}: HomeNavigationProps<"BeautifulPlacesCards">) => {
    const flatListRef = useRef(null);
    const toTop = () => {
        flatListRef.current.scrollToOffset(1)
    }
    const buttonPressed = () => {
     toTop()
    }
    return(
           <Carousel filteredData={filteredData} flatListRef={flatListRef}/>
    )
}

这是我的子组件:

const Carousel = forwardRef((filteredData, flatListRef) => {
 return (
         <AnimatedFlatList 
                  ref={flatListRef}
         />
 )
}

【问题讨论】:

    标签: reactjs react-native ref use-ref


    【解决方案1】:

    这是一个工作示例:https://snack.expo.dev/@zvona/forwardref-example

    关键时刻:

    • 传递时需要使用prop ref,而不是flatListRef
    • 你需要从 props 中解构 filteredData

    以下是相关代码:

    const Child = forwardRef(({ filteredData }, ref) => {
      return (
        <FlatList
          ref={ref}
          style={styles.flatList}
          data={filteredData}
          renderItem={({ item }) => (
            <Text style={styles.item} key={`foo-${item}`}>
              {item}
            </Text>
          )}
        />
      );
    });
    
    const App = () => {
      const flatListRef = useRef(null);
    
      const toTop = () => {
        flatListRef.current.scrollToOffset(1);
      };
    
      return (
        <View style={styles.container}>
          <Button title={'Scroll back'} onPress={toTop} />
          <Child filteredData={[1,2,3,4,5,6]} ref={flatListRef} />
        </View>
      );
    };
    

    【讨论】:

    • 非常感谢,我将flatListRef 更改为ref,现在可以使用了!
    猜你喜欢
    • 2019-08-11
    • 2020-09-19
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多