WebViewについて①

WebでのサービスをReact Nativeで使用したいときは、React.jsを経由せず、HTML(+

JavaScript)を、WebViewを使って表示させるのがよい。(使用するライブラリは、react-native-webviewである。)

この際、2つの方法がある。

【ReactNative】WebViewを使ってWebコンテンツを表示する

 

VSCodeで、htmlファイルを作成し、冒頭で、『!』を入力し、EnterにてHTMLファイルのテンプレートが自動的にできあがるようである。

 

まず、html、css、javascritp ファイルを作成する

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="./index.css" />
    <script src="./index.js"></script>
  </head>
  <body>
    <div class="title">Document</div>
    <button id="button">PUSH</button>
  </body>
</html>

index.css

@charset "utf-8";

.title {
  font-size: small;
  color: aqua;
}

index.js

window.addEventListener("load", function () {
  document.getElementById("button").onclick = function () {
    alert("Hello");
  };
});

 

React Nativeで作成します。

import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View, SafeAreaView } from "react-native";
import { WebView } from "react-native-webview";
import { SafeAreaProvider } from "react-native-safe-area-context";

const html = `
  <html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="./index.css" />
    <script src="./index.js"></script>
  </head>
  <body>
    <div class="title">Document</div>
    <button id="button">PUSH</button>
  </body>
</html>`;

export default function App() {
  return (
    <SafeAreaProvider>
      <SafeAreaView style={{ flex: 1 }}>
        <WebView source={{ html: html }} />
      </SafeAreaView>
    </SafeAreaProvider>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});