简体   繁体   中英

how can i get current y value in react-native?

When I run onPress on the TodoItem component, I want to get the position value y where the button is and write it to console.log(index).

but if i use my code this error occure: Cannot read property 'y' of undefined

how can i current position value?

how can i fix my code?

this is my code

(TodoList.js)

    const TodoList = ({}) => {

      const height = Dimensions.get('window').height;
      const flatListRef = useRef()

    return (
      <FlatList
      ref={flatListRef}
        style={{height}}
        renderItem={({item}) => (
          <TodoItem
          style={{height}}
          contentOffset={{x: 0, y: height}}
          onPress={(event) => {
          const index = event.nativeEvent.contentOffset.y
          console.log("index:",index);
          }}
          />
        )

(TodoItem.js)

    import React, { useCallback, useState } from 'react';
    import {FlatList} from 'react-native';


    const TodoItem = ({onPress}) => {


    return (
        
    
    <MainContainer onPress={onPress}>
        <Label>hi</Label>
    </MainContainer>
    import { FlatList , Dimensions } from "react-native"
    const height = Dimensions.get('window').height;
    const flatListRef = useRef()


 const TodoList = (props) => {
    return (
      <FlatList
      ref={flatListRef}
        style={{height}}
        renderItem={({item}) => (
          <TodoItem
          style={{height}}
          contentOffset={{x: 0, y: height}}
          onPress={(event) => {
          const index = event.nativeEvent.contentOffset.y
          console.log("index:",index);
          }}
          />
        )}
     }}

in your 'onPress' event you can get boundingBox data through 'event.target'

const index = event.currentTarget.getBoundingClientRect().y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM