如何在 React Native 中更改 WebView 的背景颜色?

Jas*_*len 2 react-native

我的 WebView 首先加载,然后按下 TouchableOpacity。我可以在后台 webview 更改后执行此操作而不重新启动 webview 吗?

import React, {Component} from 'react';
import {View,Text} from 'react-native'

export default class TestScreen extends Component {
render() {
return  (
    <View >
        <TouchableOpacity onPress={/*what is the function that changes the background color of the webview after loading it (but without reloading the Webview)*/}>
         <WebView>
       </TouchableOpacity>

     </View>
  );
}}
Run Code Online (Sandbox Code Playgroud)

Qin*_*ing 6

不,您无法更改 Web 视图的背景颜色,但您可以在 Web 视图上使用另一个视图并覆盖您的背景颜色。

import React from 'react';
import {View, StyleSheet, WebView, ActivityIndicator} from 'react-native';

export default class YourComponent extends React.PureComponent{

    state = {
        loading: true,
    };

    render() {
        return (
            <View>
                <WebView
                    source={html}
                    onLoadEnd={() => {
                        this.setState({loading: false});
                    }}
                />
                {
                    this.state.loading && (
                        <View style={{
                            ...StyleSheet.absoluteFillObject,
                            backgroundColor: '#000000',  // your color 
                            alignItems: 'center',
                            justifyContent: 'center',
                        }}>
                            <ActivityIndicator />
                        </View>
                    )
                }
            </View>
        )

    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

是的。你可以。通过这样做,您实际上可以更改 webview 的背景颜色。

在 WebView 开始标签中添加样式道具。像这样

<WebView 
  style={{
    backgroundColor: 'green'
  }}
/> 
Run Code Online (Sandbox Code Playgroud)

这会将 webview 的背景设置为绿色。