【问题标题】:React Native WebView if url Match show alert to exitReact Native WebView if url Match show alert to exit
【发布时间】:2022-11-02 18:17:34
【问题描述】:

当我插入条件时,如果 url 匹配以显示警报不起作用,则反应 webview 后处理程序工作正常 下面的代码是

 const [canGoBack, setCanGoBack] = useState(false);
 const [canGoForward, setCanGoForward] = useState(false);
 const [currentUrl, setCurrentUrl] = useState('');


  const onPressHardwareBackButton = () => {
 
    if (webview.current) { 
      webview.current.goBack();
       return true; 

    } else {
      return false;
    }
  
  };
 useEffect(() => {
 
        BackHandler.addEventListener('hardwareBackPress', onPressHardwareBackButton);
        return () => {
          BackHandler.removeEventListener('hardwareBackPress', onPressHardwareBackButton);
        }
    
  }, []);

<WebView 
      source={{ uri: 'https://example.com/' }} 
      ref={webview}
       onNavigationStateChange={(navState) => {
        setCanGoBack(navState.canGoBack);
        setCanGoForward(navState.canGoForward);
        setCurrentUrl(navState.url);
      }}
             />

如果CurrentUrl 匹配www.example.com/dashboard 需要提醒

  Alert.alert("Hold on!", "Are you sure you want to go back?", [
    {
      text: "Cancel",
      onPress: () => null,
      style: "cancel"
    },
    { text: "YES", onPress: () => BackHandler.exitApp() }
  ])  

怎么能做到这一点

【问题讨论】:

    标签: react-native webview


    【解决方案1】:

    您已经将当前 url 保存到状态,因此只听 currentUrl 更改就足够了。

    useEffect(() => {
        if(currentUrl === 'www.example.com/dashboard') {
            Alert.alert("Hold on!", "Are you sure you want to go back?", [
                {
                  text: "Cancel",
                  onPress: () => null,
                  style: "cancel"
                },
                { text: "YES", onPress: () => BackHandler.exitApp() }
             ]);
        }
    }, [currentUrl]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 2016-12-12
      • 2020-04-28
      相关资源
      最近更新 更多