React 原生加载 css 和 js Webview [英] React native load css and js Webview

查看:59
本文介绍了React 原生加载 css 和 js Webview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 react native 在 webview 中加载自定义 html,它适用于简单的 html,但我不知道如何将 javascript 从 js 文件加载到 webview,看起来没有任何反应.

I want to load custom html in a webview using react native, it's working for simple html but I can't figure out how to load javascript from a js file to the webview, it looks like nothing happen.

这是我的网页视图:

 var html = '<!DOCTYPE html><html><head><script src="myfile.js" type="text/javascript"></script></head><body><h1>This is a heading!</h1><div id="here"></div></body></html>';

    return (
      <WebView html={html}
               javaScriptEnabled={true} />
    );

这里有我的简单 js 文件 (myfile.js):

And here I have my simple js file (myfile.js):

document.addEventListener("DOMContentLoaded", function(event) {
   alert("HERE");
   var generateHere = document.getElementById("here");
generateHere.innerHTML = '<div class="someclass"><a href="www.example.com"><p>some text</p></a></div>';
});

我在我的网络浏览器中尝试过它可以工作.

I tried it in my web browsers it works.

推荐答案

需要使用 WebView 上的 injectedJavaScript 属性来传递 JS 来执行.

You need to use the injectedJavaScript attribute on the WebView to pass over JS to be executed.

例如:

<WebView html={html}
    injectedJavaScript={'function myfunc() { //your JS here };myfunc();'}
    javaScriptEnabled={true} /> 

这篇关于React 原生加载 css 和 js Webview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆