Authored by 孙凯

add WebView 高度自适应 review by hongmo

@@ -14,17 +14,66 @@ const { @@ -14,17 +14,66 @@ const {
14 } = ReactNative; 14 } = ReactNative;
15 15
16 16
  17 +const BODY_TAG_PATTERN = /\<\/ *body\>/;
  18 +
  19 +var script = `
  20 +;(function() {
  21 +var wrapper = document.createElement("div");
  22 +wrapper.id = "height-wrapper";
  23 +while (document.body.firstChild) {
  24 + wrapper.appendChild(document.body.firstChild);
  25 +}
  26 +document.body.appendChild(wrapper);
  27 +var i = 0;
  28 +function updateHeight() {
  29 + document.title = wrapper.clientHeight;
  30 + window.location.hash = ++i;
  31 +}
  32 +updateHeight();
  33 +window.addEventListener("load", function() {
  34 + updateHeight();
  35 + setTimeout(updateHeight, 1000);
  36 +});
  37 +window.addEventListener("resize", updateHeight);
  38 +}());
  39 +`;
  40 +
  41 +
  42 +const style = `
  43 +<style>
  44 +body, html, #height-wrapper {
  45 + margin: 0;
  46 + padding: 0;
  47 +}
  48 +#height-wrapper {
  49 + position: absolute;
  50 + top: 0;
  51 + left: 0;
  52 + right: 0;
  53 +}
  54 +</style>
  55 +<script>
  56 +${script}
  57 +</script>
  58 +`;
  59 +
  60 +const codeInject = (html) => html.replace(BODY_TAG_PATTERN, style + "</body>");
  61 +
17 export default class DetailText extends React.Component { 62 export default class DetailText extends React.Component {
18 constructor(props) { 63 constructor(props) {
19 super(props); 64 super(props);
  65 + this.handleNavigationChange = this.handleNavigationChange.bind(this);
  66 + this.state = {
  67 + realContentHeight : 10,
  68 + };
20 } 69 }
21 70
22 - shouldComponentUpdate(nextProps){  
23 - if (Immutable.is(nextProps.resource, this.props.resource)) {  
24 - return false;  
25 - } else {  
26 - return true;  
27 - } 71 + handleNavigationChange(navState) {
  72 +
  73 + let heightT = parseInt(navState.title, 10) || 0; // turn NaN to 0
  74 + this.setState({
  75 + realContentHeight: heightT,
  76 + });
28 } 77 }
29 78
30 79
@@ -33,11 +82,14 @@ export default class DetailText extends React.Component { @@ -33,11 +82,14 @@ export default class DetailText extends React.Component {
33 let template_name = resource.get('data'); 82 let template_name = resource.get('data');
34 let text = template_name.get('text'); 83 let text = template_name.get('text');
35 84
  85 + text = '<html><body>' + text + '</body></html>';
  86 +
36 return ( 87 return (
37 - <View style={{flex:1}}>  
38 - <WebView style={styles.webview_style}  
39 - source= {{html: text}} 88 + <View style={{width: width,height: this.state.realContentHeight}}>
  89 + <WebView style={{width: width,height: this.state.realContentHeight}}
  90 + source= {{html: codeInject(text)}}
40 scrollEnabled={false} 91 scrollEnabled={false}
  92 + onNavigationStateChange={this.handleNavigationChange}
41 > 93 >
42 </WebView> 94 </WebView>
43 </View> 95 </View>