首页 > 解决方案 > 如何检测组件中的堆栈导航器 goBack() 函数

问题描述

我有带有默认标题和输入组件的堆栈导航器。我想要的是当用户按下标题上的后退按钮时,检查“输入”状态是否为空,如果它不为空,则在运行 goBack() 函数之前显示模式或警报。是否可以在组件中访问此功能,或者我必须在组件中定义标题而不是 Stack.Screen?

<Stack.Navigator>
    .
    .
    .
    <Stack.Screen
    name="New"
    component={NewScreen} />
</Stack.Navigator>

我的带有样式组件的 NewScreen 组件

const NewScreen = ({ navigation }) => {
   const [input, setInput] = useState("");
   return (
      <Container>
          <TextInput
            autoFocus
            placeholder="What's happening?"
            onChangeText={setInput}
          />
      </Container>
}

标签: react-native

解决方案


最好的方法是在该组件内部制作一个自定义标题

const NewScreen = ({ navigation }) => {
   const [input, setInput] = useState("");
const alert = () =>
    Alert.alert(
      "Alert Title",
      "My Alert Msg",
      [
        {
          text: "Ask me later",
          onPress: () => console.log("Ask me later pressed")
        },
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel"
        },
        { text: "OK", onPress: () => {
              navigation.goBack();
          } }
      ],
      { cancelable: false }
    );
   return (
      <Container>
         <View style={{width: '100%', height:'30'}}>
             <ButtonIcon onPress={() => {
               if(input && input !== ''){
                   alert();
               }
             
            }}/>
          </View>
          <TextInput
            autoFocus
            placeholder="What's happening?"
            onChangeText={setInput}
          />
      </Container>
}

推荐阅读