参考http://blog.csdn.net/chichengjunma/article/details/53423689
使用发现高度计算的不对,经过排查和测试,正确地如下:
1、新建文件WebViewAutoHeight.js
/**
* WebView自适应高度
*/
importReact, {Component,propTypes}from'react';
import{WebView, View, Text}from"react-native";
constBODY_TAG_PATTERN=/\<\/ *body\>/;
// Do not add any comments to this! It will break because all line breaks will removed for
// some weird reason when this script is injected.
varscript=`
;(function() {
var wrapper = document.createElement("div");
wrapper.id = "height-wrapper";
while (document.body.firstChild) {
wrapper.appendChild(document.body.firstChild);
}
document.body.appendChild(wrapper);
var i = 0;
function updateHeight() {
document.title = wrapper.clientHeight;
window.location.hash = ++i;
}
updateHeight();
window.addEventListener("load", function() {
updateHeight();
setTimeout(updateHeight, 1000);
});
window.addEventListener("resize", updateHeight);
}());
`;
conststyle=`
body,html, #height-wrapper {
margin: 10;
padding: 0;
}
#height-wrapper {
position: absolute;
top: 0;
left: 0;
right: 0;
}
${script}
`;
constcodeInject= (html) => html.replace(BODY_TAG_PATTERN,style+"");
/**
* Wrapped Webview which automatically sets the height according to the
* content. Scrolling is always disabled. Required when the Webview is embedded
* into a ScrollView with other components.
*
* Inspired by this SO answer http://stackoverflow.com/a/33012545
* */
varWebViewAutoHeight= React.createClass({
propTypes: {
source: React.PropTypes.object.isRequired,
injectedJavaScript: React.PropTypes.string,
minHeight: React.PropTypes.number,
onNavigationStateChange: React.PropTypes.func,
style: WebView.propTypes.style,
},
getDefaultProps() {
return{minHeight:0};
},
getInitialState() {
return{
realContentHeight:this.props.minHeight,
};
},
handleNavigationChange(navState) {
if(navState.title) {
constrealContentHeight= navState.title;//parseInt(navState.title, 20) || 0; // turn NaN to 0
if(!isNaN(realContentHeight)){
this.setState({realContentHeight});
}
}
if(typeof this.props.onNavigationStateChange==="function") {
this.props.onNavigationStateChange(navState);
}
},
render() {
const{source,style,minHeight, ...otherProps} =this.props;
consthtml=source.html;
if(!html) {
throw newError("WebViewAutoHeight supports only source.html");
}
if(!BODY_TAG_PATTERN.test(html)) {
throw newError("Cannot find from: "+html);
}
return(
{...otherProps}
source={{html:codeInject(html)}}
scrollEnabled={false}
style={[style, {height:Math.max(this.state.realContentHeight,minHeight)}]}
javaScriptEnabled
onNavigationStateChange={this.handleNavigationChange}
/>
);
},
});
export defaultWebViewAutoHeight;
2、使用
import WebViewAutoHeight from '../components/WebViewAutoHeight';
constructor(props) {
super(props);//这一句不能省略,照抄即可
this.state= {
height:0,
};
}