【问题标题】:React Native - Webview call React Native functionReact Native - Webview 调用 React Native 函数
【发布时间】:2016-12-26 09:04:00
【问题描述】:

是否可以在WebView 组件内部创建一个函数,触发 React Native 函数?

【问题讨论】:

  • 您到底想达到什么目标? React native 非常强大,它使用原生 android 或 ios API 来增强使用 React native 构建应用程序的能力。在不使用 WebView 的情况下,可能还有一些其他的好方法。
  • 您能否更具体地了解您的要求

标签: javascript react-native


【解决方案1】:

这是可能的,但我不确定这是否是唯一的方法。

基本上你可以设置一个onNavigationStateChange事件处理程序,并在导航url中​​嵌入函数调用信息,这里是一个概念的例子。

在 React Native 上下文中

render() {

    return <WebView onNavigationStateChange={this._onURLChanged.bind(this)} />
}

_onURLChanged(e) {

    // allow normal the natvigation
    if(!e.url.startsWith('native://'))
        return true
    var payload = JSON.parse(e.url.replace('native://', ''))
    switch(e.functionName) {
        case 'toast' :
            native_toast(e.data)
        break
        case 'camera' :
            native_take_picture(e.data)
        break
    }
    // return false to prevent webview navitate to the location of e.url
    return false

}

调用native方法,使用这个只是触发webview的导航事件,并在URL中嵌入函数调用信息。

window.location = 'native://' + JSON.stringify({ 
    functionName : 'toast', data : 'show toast text' 
})

【讨论】:

  • 只有我还是这会在android上抛出ERR_UNKNOWN_URL_SCHEME
【解决方案2】:

您可以在加载时向 webview 注入一个 javascript 函数,然后使用 onMessage 从您注入的函数中获取响应更多信息IN Here

【讨论】:

    【解决方案3】:

    &lt;WebView/&gt;上使用onMessage eventListner

    <WevView onMessage={onMessage} ... />
    
    /** on message from webView -- window.ReactNativeWebView?.postMessage(data) */
      const onMessage = event => {
        const {
          nativeEvent: {data},
        } = event;
    
        if (data === 'goBack') {
          navigation.goBack();
        } else if (data?.startsWith('navigate')) {
          // navigate:::routeName:::stringifiedParams
          try {
            const [, routeName, params] = data.split(':::');
            params = params ? JSON.parse(params) : {};
            navigation.navigate(routeName, params);
          } catch (err) {
            console.log(err);
          }
        }
      };
    

    在您的 HTML 中使用它来发布消息事件

    window.ReactNativeWebView?.postMessage("data")
    

    【讨论】:

    • 从“react-native-webview”导入 {WebView}
    【解决方案4】:

    是的,这是可能的,它为 react-native-webview-bridge 提供了一个包。 我在生产中大量使用它,它工作得很好。

    【讨论】:

    【解决方案5】:

    我不确定,但我的看法是——

    你不能。 Webview 只能加载我们可以在 Webview 组件中定义的 js 部分。这与其他组件完全分开,它只是一个可视区域。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-08
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      相关资源
      最近更新 更多