如何在 React Native 中动态创建多个 Refs

How to create multiple Refs dynamically in React Native

我的 React Native 应用程序中有多个 Swipeable 组件,它们由用户动态创建,为了让 Swipeable 自行关闭,我设置了对它的引用,并调用了关闭函数但是,这仅适用于最后创建的 Swipeable,而不适用于所有 Swipeable,我怎样才能使 ref 应用于所有这些?

这是我的代码:

const [messages, setMessages] = useState([])
const Swipeablee = useRef();

     return(
 {messages.map(({id, data}) => (
 <Swipeable key={id} renderLeftActions={leftActions}
                onSwipeableLeftOpen={() => swipeAction(data)}
                overshootLeft={false}
                ref={Swipeablee}
                overshootFriction={8} >
)}
)

这是我正在调用的函数:

const swipeAction = (data) => {

        Swipeablee.current.close()
  }

这里是你如何做到这一点。使用 useRef 创建一个数组,并在 Swipeable 组件渲染后将 ref 存储在其中。

const [messages, setMessages] = useState([]);
const refs = useRef([]); // using useRef because we want to persist the values when component re-renders

const swipeAction = (data, swipeable) => {
  // process data
  swipeable.close()
}


return(
   {messages.map(({id, data}, index) => (
      <Swipeable key={id} renderLeftActions={leftActions}
            onSwipeableLeftOpen={() => swipeAction(data, refs.current[index])}
            overshootLeft={false}

            // Store the Swipeable to our array, ref prop will give us the component once it is rendered
            ref={swipeable => refs.current[index] = swipeable}

            overshootFriction={8} />
    )}
)