知识点 WebView
第一种: WebView直接加载一个url来展示网页。 观察新闻数据,我们发现有一个3g网页的url
{ "url_3w": "http://ent.163.com/16/0815/15/BUH64L0J00031H2L.html", "postid": "BUH64L0J00031H2L", "votecount": 49276, "replyCount": 51267, "ltitle": "知情人称王宝强借钱是因账户大笔钱一日内被取走", "digest": "网易娱乐8月15日报道15日上午9时许,王宝强本人在律师张起淮的陪同下来到北京朝阳法院,起诉其妻马蓉要求离婚。据悉,朝阳法院经审查符合立案条件,已正式受理此案。", "url": "http://3g.163.com/ent/16/0815/15/BUH64L0J00031H2L.html", "docid": "BUH64L0J00031H2L", "title": "知情人称王宝强借钱是因账户大笔钱一日内被取走", "source": "网易娱乐", "priority": 162, "lmodify": "2016-08-15 15:52:00", "imgsrc": "http://cms-bucket.nosdn.127.net/9ed8283f475445c4868faba9b72c730620160815153433.png", "subtitle": "", "boardid": "ent2_bbs", "ptime": "2016-08-15 15:30:46" },1、Component/NewsDatail.js新闻详情页
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, WebView, } from 'react-native'; var NewsDetail = React.createClass({ render() { return ( <WebView automaticallyAdjustContentInsets={true} source={{uri: this.props.rowData.url}} /> ); } }); const styles = StyleSheet.create({ }); // 输出类 module.exports = NewsDetail;在Home.js里,传过去了新闻数据rowData
// 点击cell跳转到新闻详情页面 pushToNewsDetail(rowData){ this.props.navigator.push({ component:NewsDetail, title:rowData.title, passProps:{rowData} }) },2、所以在NewsDetail.js里面 WebView直接加载rowData.url
<WebView automaticallyAdjustContentInsets={true} source={{uri: this.props.rowData.url}} />第二种:拼接html http://c.3g.163.com/nc/article/BUH64L0J00031H2L/full.html 观察这个地址,BUH64L0J00031H2L 就是每条新闻数据里的postid。 下面我们要取出里面的 html代码,然后拼接。 1.NewsDetail.js全部代码:
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, WebView, } from 'react-native'; var NewsDetail = React.createClass({ getInitialState(){ return{ // 具体的数据 datailData:'' } }, render() { return ( <WebView automaticallyAdjustContentInsets={true} source={{html:this.state.datailData, baseUrl:''}} /> ); }, componentDidMount(){ // 请求的路径 var url_api = 'http://c.3g.163.com/nc/article/'+ this.props.rowData.postid +'/full.html'; // 发送请求 fetch(url_api) .then((response)=>response.json()) .then((responseData)=>{ // 处理json数据 var allData = responseData[this.props.rowData.postid]; // 取出body var bodyHtml = allData['body']; // 取出图片数据 if(allData['img'].length > 0){ for(var i=0;i<allData['img'].length;i++){ // 取出单个图片对象 var img = allData['img'][i]; // 取出图片的src var imgsrc = img['src']; // 拼接html var imgHtml = '<img src="'+imgsrc+'" width="100%"/>'; // 替换body中的图像占位符 bodyHtml = bodyHtml.replace(img['ref'],imgHtml); } } // 更新状态机 this.setState({ datailData:bodyHtml, }); }) .catch((error)=>{ console.log('请求数据失败'); }) }, }); const styles = StyleSheet.create({ }); // 输出类 module.exports = NewsDetail;2.效果
