React-Native学习笔记之:WebView控件使用

前端之家收集整理的这篇文章主要介绍了React-Native学习笔记之:WebView控件使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
和Android及IOS一样,在React Native中也有加载网页数据的控件WebView,常用的方法有:
  • source {uri: string,method: string,headers: object,body: string},{html: string,baseUrl: string},number
    在WebView中载入一段静态的HTML代码或是一个url(还可以附带一些header选项)。@H_301_6@
  • onError function 方法 当网页加载失败的时候调用@H_301_6@
  • onLoad function 方法 当网页加载结束的时候调用@H_301_6@
  • onLoadEnd fucntion 当网页加载结束调用,不管是成功还是失败@H_301_6@
  • onLoadStart function 当网页开始加载的时候调用@H_301_6@
  • onNavigationStateChange function方法 当导航状态发生变化的时候调用@H_301_6@
  • renderError function 该方法用于渲染一个View视图用来显示错误信息@H_301_6@
  • renderLoagin function 该方法用于渲染一个View视图用来显示一个加载进度指示器等。
    使用DEMO(在输入框中输入网页地址,点击GO进行加载对应网页)如下:@H_301_6@
import React,{Component} from 'react';
import {
    AppRegistry,StyleSheet,Text,View,TextInput,WebView
} from 'react-native';
//引入easy-toast依赖库
import Toast,{DURATION} from 'react-native-easy-toast'
export  default @H_403_40@class WebViewDemo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            url: 'http://blog.csdn.net/true100',title: '',canBack: false
        }
    }

    onBack() {
        //如果网页还有上级页面(可返回)
        if (this.state.canBack) {
            this.webView.goBack();
        } else {
            //提示不能返回上一页面了
            this.toast.show('再点击就退出啦',DURATION.LENGTH_SHORT);
        }
    }

    onNext() {
        this.setState({
            //设置请求地址
            url: this.text
        })
    }

    onNavigationStateChange(e) {
        this.setState({
            title: e.title,//设置是否要以返回上级页面
            canBack: e.canGoBack
        })
    }

    render() {
        return <View style={styles.container}>
            <View style={styles.item}>
                <Text style={styles.text} onPress={()=>{this.onBack()}}>返回</Text>
                <TextInput style={styles.input}
                           defaultValue={'http://blog.csdn.net/true100'}
                           onChangeText={text=>this.text=text}></TextInput>
                <Text style={styles.text} onPress={()=>{this.onNext()}}>GO</Text>
            </View>
            <WebView source={{uri:this.state.url}}
                     onNavigationStateChange={(e)=>this.onNavigationStateChange(e)}
                     ref={webView=>this.webView=webView}></WebView>
            <Toast ref={toast=>{
                       this.toast=toast
                    }}/>
        </View>
    }
}

const
    styles = StyleSheet.create({
        container: {
            flex: 1
        },text: {
            fontSize: 20,color: '#333',marginLeft: 10
        },input: {
            height: 40,marginLeft: 10,flex: 1,borderWidth: 1
        },item: {
            flexDirection: 'row',alignItems: 'center',paddingTop: 10,marginRight: 10
        }
    })

效果如图:

原文链接:https://www.f2er.com/react/304424.html

猜你在找的React相关文章