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
this.webview.injectJavaScript(injectedJavaScriptCode)
}
render() {
const { title, html, data } = this.props
const { SIGN, UPDATE_TIME } = this.props.data
const addHtml1 = '
const addHtml2 = '\n
const html1 = addHtml1 + title + addHtml2
const addHtml3 = '
const addHtml4 = '
const addHtml44 = '
const addHtml5 = '
const addHtml6 = '
const html2 = addHtml3 + addHtml4 + SIGN + addHtml5 + addHtml44 + UPDATE_TIME.substr(0, 10) + addHtml5 + addHtml6
const HTMLText = html1 + html2 + html
return (
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
/>
)
}
}
const state = (state) => ({
userInfo: state.userInfo
})
export default connect(state)(WebViewHTML)
const styles = StyleSheet.create({
container: {
flex: 1
},
text: {
color: '#aab2b1',
fontSize: 12
}
})
本文介绍如何解决React Native中WebView组件加载H5页面时遇到的样式问题,如图片超出屏幕和文本大小不匹配等。通过注入JavaScript代码进行样式调整,并提供了一个具体的实现案例。
1119

被折叠的 条评论
为什么被折叠?



