导航到不同屏幕时底部 Sheet 不会关闭

Bottom Sheet doesn't close when navigating to different screen

我是编程新手,当我导航到新屏幕时底部 sheet 没有关闭 here's the picture of it。我正在使用 @gorhom/bottom-sheet^4。我做了一些研究,我知道使用 useFocusEffect 可以实现它,但我真的不知道如何实现。有人可以帮我解决这个问题吗?

<BottomSheetModal
    enablePanDownToClose={true}
    ref={bottomSheetModalRef}
    index={0}
    snapPoints={snapPoint}
    backdropComponent={renderBackdrop}
  >
    <View>
      <TouchableWithoutFeedback
        onPress={() => {
          navigation.navigate("Settings");
        }}
      >
        <Text style={styles.modalText}>Settings</Text>
      </TouchableWithoutFeedback>
      <TouchableWithoutFeedback
        onPress={() => {
          navigation.navigate("Saved");
        }}
      >
        <Text style={styles.modalText}>Saved</Text>
      </TouchableWithoutFeedback>
      <TouchableWithoutFeedback
        onPress={() => {
          navigation.navigate("Delete");
        }}
      >
        <Text style={styles.modalText}>Delete</Text>
      </TouchableWithoutFeedback>
      <TouchableWithoutFeedback onPress={() => {}}>
        <Text style={styles.modalText}>Log out</Text>
      </TouchableWithoutFeedback>
    </View>
  </BottomSheetModal>

有几种方法可以做到。这里有两个:

  1. 添加 useFocusEffect 当您的 BottomSheetModal 屏幕未聚焦时运行:
useFocusEffect(
  React.useCallback(() => {
    return () => bottomSheetRef.current?.close()
  }, [])
);
  1. 关闭 BottomSheetModal,每当您离开屏幕时。为此,您必须在导航时调用 bottomSheetModalRef.current?.close

    <TouchableWithoutFeedback
     onPress={() => {
       navigation.navigate("Settings");
       bottomSheetModalRef.current?.close();
     }}
    >
     <Text style={styles.modalText}>Settings</Text>
    </TouchableWithoutFeedback>
    <TouchableWithoutFeedback
     onPress={() => {
       navigation.navigate("Saved");
       bottomSheetModalRef.current?.close();
     }}
    >
     <Text style={styles.modalText}>Saved</Text>
    </TouchableWithoutFeedback>
    <TouchableWithoutFeedback
     onPress={() => {
       navigation.navigate("Delete");
       bottomSheetModalRef.current?.close();
     }}
    >
     <Text style={styles.modalText}>Delete</Text>
    </TouchableWithoutFeedback>