説明なし

App.js 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import React, {useState, useRef} from 'react';
  2. import {View, Text, StatusBar, Button} from 'react-native';
  3. import {WebView} from 'react-native-webview';
  4. const App = () => {
  5. const ref = useRef(undefined);
  6. const [hello, setHello] = useState(false);
  7. const html = `
  8. <!DOCTYPE html>
  9. <html lang="en">
  10. <head>
  11. <title>WebTest web view</title>
  12. <script>
  13. function sendData() {
  14. window.ReactNativeWebView.postMessage("Hey!")
  15. }
  16. </script>
  17. <style>
  18. main {
  19. padding: 150px;
  20. font-size: 50px;
  21. }
  22. main button {
  23. font-size: 40px;
  24. }
  25. </style>
  26. </head>
  27. <body>
  28. <main>
  29. <h1>Hello, World!</h1>
  30. <button onClick="sendData()">Send Data</button>
  31. </div>
  32. </main>
  33. </html>
  34. `;
  35. const triggerHello = () => {
  36. ref.current.injectJavaScript('sendData(); true');
  37. };
  38. return (
  39. <>
  40. <StatusBar barStyle="dark-content" />
  41. <WebView
  42. testID="test_webview"
  43. source={{html}}
  44. ref={ref}
  45. style={{
  46. flex: 3,
  47. }}
  48. onMessage={event => {
  49. setHello(true);
  50. }}
  51. />
  52. <View style={{flex: 1}}>
  53. {hello ? (
  54. <Text testID="hello">Hello from the webview!</Text>
  55. ) : (
  56. <Text testID="hello">No hello yet</Text>
  57. )}
  58. <Button
  59. testID="test_trigger_button"
  60. onPress={triggerHello}
  61. title="Trigger Hello"
  62. />
  63. </View>
  64. </>
  65. );
  66. };
  67. export default App;