【问题标题】:React Native getElementById反应本机 getElementById
【发布时间】:2018-03-05 20:34:16
【问题描述】:

想做一个

document.getElementById('js-pjax-loader-bar')

来自https://github.com/facebook/react-native

我不知道怎么得到它!

我试试:

const jsCode = "document.getElementById('js-pjax-loader-bar')";
return (     
  <WebView
    source={{uri: 'https://github.com/facebook/react-native'}}
    onMessage={this._onMessage}
    injectedJavaScript={jsCode }
    style={{marginTop: 20}}
  />
);

可能脚本运行​​了,但我不知道如何得到结果。

【问题讨论】:

  • 您在这些文档中在哪里看到document.getElementById?你可能想要exportimport 你想要传递的东西。
  • @Icaro Rios:我需要你的解决方案

标签: javascript reactjs react-native webview request


【解决方案1】:

React 是一个虚拟 dom,渲染后生成 bundle(客户端渲染)用于使用 ids 或类似的东西最好在 react 中使用 ref

【讨论】:

    【解决方案2】:

    我认为您需要将 javaScriptEnabled 属性设置为 true 并使用 setTimeout 来等待 DOM 加载。

    const jsCode = "setTimeout(function() {document.getElementById('js-pjax-loader-bar');}, 2000)";
    

    还有网页视图

    <WebView
        javaScriptEnabled={true}  
        source={{uri: 'https://github.com/facebook/react-native'}}
        onMessage={this._onMessage}
        injectedJavaScript={jsCode }
        style={{marginTop: 20}}
    />
    

    也可以在jsCode里面加一个alert来测试。

    要接收 _onMessage 函数,您需要使用 window.postMessage

    const jsCode = "setTimeout(function(){window.postMessage(JSON.stringify(document.getElementById('js-pjax-loader-bar')),'https://github.com/facebook/react-native');}, 2000)";
    

    而且 _onMessage 必须是这样的

    _onMessage(data) {
        var element = JSON.parse(data.nativeEvent.data);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2016-04-18
      • 2021-12-26
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多