react-native-reanimated,将组件作为 prop 传递并设置动画关闭

knpiaxh1  于 2022-12-14  发布在  React
关注(0)|答案(1)|浏览(146)

我有一个使用react-native-reanimated的组件,如何将hideSheet()添加到作为属性传递的组件中?

import Animated, { Easing } from "react-native-reanimated";
...

const BottomSheet = ({
    children,
    ...
    renderHeader,...
}) => {
    const style = useMemo(
        () => getStyleObj({ backgroundColor, secondSnapshot }),
        [backgroundColor, secondSnapshot]
    );
    const [alignment] = useState(new Animated.Value(0));
    const [alignmentChildren] = useState(new Animated.Value(0));
    const [open, setOpen] = useState(true);
    const WrapperComponent = tapToOpenEnabled ? Pressable : View;

    const openSheet = () => {
        Animated.timing(alignment, {
            toValue: 1,
            duration: 400,
            easing: Easing.bezier(0.25, 0.1, 0.25, 1),
        }).start();
    };

    const hideSheet = () => {
        Animated.timing(alignment, {
            toValue: 0,
            duration: 400,
            easing: Easing.bezier(0.25, 0.1, 0.25, 1),
        }).start();
    }; 
const toggleOpen = () => {
    if (open) {
        hideSheet();
        setOpen(false);
    } else {
        openSheet();
        setOpen(true);
    }
};

我将header组件作为prop传递:

const renderSheetHeader = useCallback(() => {
    return (
      <View style={styles.headerCont}>
        <Text style={styles.headerTXT}>Setup your reminders</Text>
        <Icon name="closecircle" size={20} color={colors.GREYONE} *add hideSheet here* />
      </View>
    );
  }, []);

  return (
    <BottomSheet
      ...
      renderHeader={renderSheetHeader()}
      ...
    >

return (
    <WrapperComponent>
       ...
                {renderHeader}
a8jjtwal

a8jjtwal1#

您可以将它作为参数传递给函数。

const renderSheetHeader = useCallback((onHide) => {
    return (
      <View style={styles.headerCont}>
        <Text style={styles.headerTXT}>Setup your reminders</Text>
              <View style={styles.headerCont}>
        <Text style={styles.headerTXT}>Setup your reminders</Text>
        <Pressable onPress={() => onHide()}>
            <Icon name="closecircle" size={20} color={colors.GREYONE} />
        </Pressable>
      </View>
      </View>
    );
  }, []);

然后,照常打电话。

<WrapperComponent>
       ...
                {(onHide) => renderHeader(onHide)}

在您的WrapperComponent中:

renderHeader(hideSheet)

但是,如果您没有必要将其定义为函数(并且我在您当前的代码中看不出有什么理由),那么您最好只创建一个normaleJSX组件。

export function SheetHeader(props) {
  return (
      <View style={styles.headerCont}>
        <Text style={styles.headerTXT}>Setup your reminders</Text>
              <View style={styles.headerCont}>
        <Text style={styles.headerTXT}>Setup your reminders</Text>
        <Pressable onPress={() => onHide()}>
            <Icon name="closecircle" size={20} color={colors.GREYONE} />
        </Pressable>
      </View>
      </View>
    );
}

并直接在WrapperComponent中调用它。

<SheetHeader onHide={hideSheet} />

相关问题