RN的WebView组件加载H5代码可能会出现一些样式问题,比如图片超出手机屏幕、文本大小样式问题。下面总结了一下,如何在WebView里面加入我们的标签代码以及样式适配。
class WebViewHTML extends Component {
constructor(props) {
super(props)
this.state = {
}
}
componentWillMount() {
}
componentDidMount() {
const injectedJavaScriptCode = `var objs = document.getElementsByTagName('img');for(var i=0;i<objs.length;i++){var img = objs[i];img.style.width = '100%';}`
this.webview.injectJavaScript(injectedJavaScriptCode)
}
render() {
const { title, html, data } = this.props
const { SIGN, UPDATE_TIME } = this.props.data
const addHtml1 = '<div style=\"font-family:sans-serif;font-size:20px;color:#333\">\n\t'
const addHtml2 = '\n</div>\n'
const html1 = addHtml1 + title + addHtml2
const addHtml3 = '<div style=\"font-size:12px;color:#aab2b1;display:flex;align-items:center;\">'
const addHtml4 = '<div style=\"margin-left:2px;\">'
const addHtml44 = '<div style=\"margin-left:20px;\">'
const addHtml5 = '</div>'
const addHtml6 = '</div>\n'
const html2 = addHtml3 + addHtml4 + SIGN + addHtml5 + addHtml44 + UPDATE_TIME.substr(0, 10) + addHtml5 + addHtml6
const HTMLText = html1 + html2 + html
return (
<View style={styles.container}>
<View style={{ backgroundColor: theme.bg_color }}>
<NavbarView title={title} isLoop={true} />
</View>
<View style={{ flex: 1 }}>
<WebView
ref={p => this.webview = p}
source={{ html: HTMLText, baseUrl: '' }}
style={{ flex: 1, width: SCREEN_WIDTH }}
automaticallyAdjustContentInsets={false}
javaScriptEnabled={true}
saveFormDataDisabled={true}
scalesPageToFit={Platform.OS === 'android' ? false : true}
// useWebKit={true}
scrollEnabled={false}
onMessage={event => {
// alert(event.nativeEvent.data);
}}
contentInset={{ top: 0, left: 0, right: 0, bottom: 0 }}
injectedJavaScript={`
const meta = document.createElement('meta');
meta.setAttribute('content', 'initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width');
meta.setAttribute('name', 'viewport');
document.getElementsByTagName('head')[0].appendChild(meta);`+`var objs = document.getElementsByTagName('img');for(var i=0;i<objs.length;i++){var img = objs[i];img.style.width = '100%';}`}
/>
</View>
</View>
)
}
}
const state = (state) => ({
userInfo: state.userInfo
})
export default connect(state)(WebViewHTML)
const styles = StyleSheet.create({
container: {
flex: 1
},
text: {
color: '#aab2b1',
fontSize: 12
}
})