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 = '

\n\t'

const addHtml2 = '\n

\n'

const html1 = addHtml1 + title + addHtml2

const addHtml3 = '

'

const addHtml4 = '

'

const addHtml44 = '

'

const addHtml5 = '

'

const addHtml6 = '

\n'

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

}

})

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐