React Native实现简单的浏览器,同时兼容android和IOS平台。实现最基本的功能:地址,前进,后退,刷新。为了方便学习,copy用,尽可能用最基本的组件实现,没有引用icon图标之类的可以美化界面的组件。希望对学习react-native-webview的同学有些帮助。
react-native-webview组件在大部分APP中都要用到,毕竟web页面很强大。加油打工人!
知识点
- react-native-webview组件的安装与简单的使用
- 简单的布局,更多的布局知识:https://www.reactnative.express/core_components/layout
效果展示
安装react-native-webview
yarn add react-native-webview
或者
npm install --save react-native-webview
详细请参照:https://github.com/react-native-webview/react-native-webview/blob/master/docs/Getting-Started.md
具体实现代码
/* eslint-disable prettier/prettier */
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React,{useState} from 'react';
import {
SafeAreaView,
StyleSheet,
Text,
View,
Button,
TextInput,
} from 'react-native';
import WebView from 'react-native-webview';
const App = () => {
const [url,setUrl] = useState('http://www.baidu.com');
const [webView,setWebview] = useState(null);
const [urlInput,setUrlInput] = useState(url);
//页面加载完成触发
const webViewOnLoad = (syntheticEvent) => {
const {nativeEvent} = syntheticEvent;
const curl = nativeEvent.url;
//根据url地址判断刚才已经完成什么操作
const jmurl = decodeURIComponent(curl);
setUrlInput(jmurl);
console.log("网页加载完成,地址是:"+jmurl)
};
//接收web发送过来的信息
const onMessage = (event) => {
const rep = event.nativeEvent.data;
//console.log('-----------webview返回结果--------------');
let minLog = rep;
if (rep.length > 300) {
minLog = rep.substring(0, 290); //日志太长影响观感
}
console.log(minLog);
};
return (
<SafeAreaView style={{flex:1}}>
<View style={{height:40,flexDirection:'row',justifyContent:'space-between'}}>
<TextInput
style={{flex:1, height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => setUrlInput(text)}
value={urlInput}
/>
<Button title={"转到"} onPress={()=>{
setUrl(urlInput);
}}/>
</View>
<WebView source={{uri: url}}
ref={(webView) => (setWebview(webView))}
sharedCookiesEnabled={true}
startInLoadingState={true}
onLoad={webViewOnLoad}
onMessage={onMessage}
onError={syntheticEvent => {
const {nativeEvent} = syntheticEvent;
console.log('网络连接失败!');
console.warn('WebView error: ', nativeEvent);
}}
/>
<View style={{flexDirection:'row',justifyContent:'space-between',height:40,backgroundColor:'white'}}>
<Button title={"主页"} onPress={()=>{
setUrl('http://www.baidu.com?t='+new Date().getTime());
}}/>
<Button title={"后退"} onPress={()=>{
webView.goBack();
}}/>
<Button title={"前进"} onPress={()=>{
webView.goForward();
}}/>
<Button title={"刷新"} onPress={()=>{
webView.reload();
}}/>
</View>
</SafeAreaView>);
};
const styles = StyleSheet.create({
});
export default App;
参考文档:
https://github.com/react-native-webview/react-native-webview/blob/master/docs/Reference.md