如何将React集成到React Native WebView中?

时间:2019-03-07 15:11:23

标签: reactjs react-native webview

我正在开发一个React Native项目。 我有一个(唯一的)React组件,我必须将其集成到我的React Native应用程序中。 我已经尝试过使用React Native WebView,但是在ReactDOM上出现错误。

是否可以与React Native Web View集成? 谢谢

反应原生

import React from "react"
import { WebView } from 'react-native'

class TVView extends React.Component{
    render(){
        return (
            <WebView
                source={require('../TV/Resources/public/index.html')}
                injectedJavaScript={require('../TV/Resources/src/index.html')}
                style={{flex: 1}}
                />
        );
    }
}

export default TVChartView

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">      
        <title>Demo</title>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>

index.js

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
    React.createElement(App),
    document.getElementById('root')
);

App.js

import * as React from 'react';
import './App.css';
import { TVContainer } from './components/TVContainer/index';

class App extends React.Component {
    render() {
        return (
            <div className={ 'App' }>
                <header className={ 'App-header' }>
                    <h1 className={ 'App-title' }>
                       Example
                    </h1>
                </header>
                <TVContainer />
            </div>
        );
    }
}

export default App;

1 个答案:

答案 0 :(得分:0)

首先在本地主机上运行 React 项目,然后下载库 react-native-webview (https://www.npmjs.com/package/react-native-webview) 因为 react-native 已弃用 WebView。 示例:-

import React from "react"
import {WebView} from 'react-native-webview';

class TVView extends React.Component{
    render(){
        return (
            <WebView
                source={{uri:'localhost:3000/}}
                injectedJavaScript={`const meta = document.createElement('meta'); meta.setAttribute('content', 'width=device-width, initial-scale=0.5, maximum-scale=0.5, user-scalable=0'); meta.setAttribute('name', 'viewport'); document.getElementsByTagName('head')[0].appendChild(meta); `}

                style={{flex: 1}}
                />
        );
    }
}

export default TVChartView