WebView 上的 React Native ref.injectJavascript 始终未定义

waf*_*ffl 9 javascript reactjs react-native

我有一个简单的功能组件,在 TabNavigator 内有一个 WebView,我想在选项卡聚焦时注入一些 javascript,如下所示:

import React, {useRef, useEffect} from 'react';
import {WebView} from 'react-native-webview';

export default (props) => {

  const webViewRef = useRef();

  React.useEffect(() => {
    const unsubscribe = props.navigation.addListener('focus', () => {
      webViewRef.current.injectJavascript('console.log("Hello World")');
    });
    return unsubscribe;
  }, []);

  return (
    <WebView ref={webViewRef} />
  );
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,webViewRef在侦听器中始终未定义。

如果我做类似的事情,<WebView ref={(r) => console.log(r)} />我会得到类似以下的结果:

截屏

编辑:

只需调整提供的示例就可以了,所以我想我必须弄清楚我的代码中发生了什么:

import React, { useRef } from 'react'
import { View } from 'react-native'
import { WebView } from 'react-native-webview'

export default () => {

  const webViewRef = useRef(null);

  const run = `
    document.body.style.backgroundColor = 'blue';
    true;
  `

  setTimeout(() => {
    webViewRef.current.injectJavaScript(run)
  }, 3000)

  return (
    <View style={{ flex: 1 }}>
      <WebView
        ref={webViewRef}
        source={{
          uri:
            'https://github.com/react-native-community/react-native-webview',
        }}
      />
    </View>
  )
}
Run Code Online (Sandbox Code Playgroud)

编辑2:调整简单的示例并尝试在侦听器内使用 ref 不起作用:

import React, { useRef } from 'react'
import { View } from 'react-native'
import { WebView } from 'react-native-webview'

export default (props) => {

  const webViewRef = useRef(null);



  const run = `
    document.body.style.backgroundColor = 'blue';
    true;
  `
  const handleLoadEnd = () => {
    props.navigation.addListener('focus', () => {
      webViewRef.current.injectJavascript(run)
    })
  }

  return (
    <View style={{ flex: 1 }}>
      <WebView
        ref={webViewRef}
        source={{
          uri:
            'https://github.com/react-native-community/react-native-webview',
        }}
        onLoadEnd={handleLoadEnd}
      />
    </View>
  )
}
Run Code Online (Sandbox Code Playgroud)

编辑3:useFocusEffect也有同样的问题:

  useFocusEffect(
    React.useCallback(() => {
      webViewRef.current.injectJavascript('alert("HI")')
    }, [props.navigation])
  )
Run Code Online (Sandbox Code Playgroud)

资料来源:

waf*_*ffl 21

天哪,这真是又一个史诗般的令人揪心的日子:

  webViewRef.injectJavascript < BAD
  webViewRef.injectJavaScript < GOOD
Run Code Online (Sandbox Code Playgroud)

请有人把我生命中最后的四个小时还给我