React-Native WebView控件使用

2017-07-05  本文已影响0人  董董董董董董董董董大笨蛋
和Android及IOS一样,在React Native中也有加载网页数据的控件WebView,常用的方法有:
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 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
        }
    })
image.png
上一篇 下一篇

猜你喜欢

热点阅读