我的React Native应用程序中有多个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} />
)}
)