我有一個帶有打開和關閉功能的可滑動組件,我想從組件的子級觸發。我不認為在這種情況下使用狀態來執行此操作是正確的,因為我想避免在可滑動組件影片時重新渲染(如果我錯了,請糾正我)。
我正在使用 react-native-gesture-handler/swipeable 并在此處遵循他們的示例
刷卡組件
import React, { useRef } from 'react';
import { RectButton } from 'react-native-gesture-handler';
import Swipeable from 'react-native-gesture-handler/Swipeable';
import Animated from 'react-native-reanimated';
const AnimatedView = Animated.createAnimatedComponent(View);
export const SwipeCard = ({ children }) => {
let swipeableRow = useRef(null);
let renderRightActions = (_progress, dragX) => {
let scale = dragX.interpolate({
inputRange: [-80, 0],
outputRange: [1, 0],
extrapolate: 'clamp',
});
return (
<RectButton style={styles.rightAction} onPress={close}>
{/* Change it to some icons */}
<AnimatedView style={[styles.actionIcon]} />
</RectButton>
);
};
let close = () => {
swipeableRow?.close();
};
let open = () => {
swipeableRow?.openRight();
};
return (
<Swipeable
ref={swipeableRow}
renderRightActions={renderRightActions}
friction={2}
rightThreshold={40}
>
{children}
</Swipeable>
);
};
下面是我使用 SwipeCard 的組件,這Toggle是我想用來觸發 SwipeCard 組件中的 open() 方法的事件。
<Row>
{arr.map((item) => {
return (
<SwipeCard key={item.id}>
<CardContainer>
<CleaningCard
cleaningData={item}
/>
<Toggle onPress={() => {}}>
<Icon name="dots" />
</Toggle>
</CardContainer>
</SwipeCard>
);
})}
</Row>
uj5u.com熱心網友回復:
您可以使用 render prop 模式和 pass close,open作為引數。
父組件在哪里SwipeCard使用:
<Row>
{arr.map((item) => {
return (
<SwipeCard key={item.id}>
{({ close, open }) => (
<CardContainer>
<CleaningCard cleaningData={item} />
<Toggle
onPress={() => {
// close()/open()
}}
>
<Icon name="dots" />
</Toggle>
</CardContainer>
)}
</SwipeCard>
);
})}
</Row>;
SwipeCard零件:
<Swipeable
ref={swipeableRow}
renderRightActions={renderRightActions}
friction={2}
rightThreshold={40}
>
{children({close, open})}
</Swipeable>
我們只是簡單地創建children一個接受一個物件并回傳 JSX 的函式。所需物件作為引數 ( children({close, open}))傳遞。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/421073.html
標籤:
