1、webview高度不能自适应,必须设置死,可以在html种执行js,获取document的高度,然后通过postmessage,通知页面给webview组件设置高度
2、字体显示非常小,这是因为webview是以PC的形式展示内容,加上viewport以及手机下的缩放设置即可。
3、字体颜色是黑色的,但是app是深色主题的app,导致文字看不清楚,总不能指望后台添加富文本时,把文字都设置成白色吧,只能前端解决。可以给html内容设置一段css,强制将文字都改成白色。
既然上面的三个问题都有解决方案,那么就开始了:
1、先定义高度
const [webviewHeight, setWebviewHeight] = useState(1);2、设置html富文本高度、文字缩放
const INJECTEDJAVASCRIPT = `
//这是缩放的
const meta = document.createElement('meta');
meta.setAttribute('content', 'initial-scale=0.5, maximum-scale=0.5, user-scalable=0');
meta.setAttribute('name', 'viewport');
document.getElementsByTagName('head')[0].appendChild(meta);
//高度获取
//let webHeight = document.body.getBoundingClientRect().height;
let webHeight = document.body.scrollHeight;
window.ReactNativeWebView.postMessage(webHeight);
`;
3、写个监听函数,设置webview的高度值
const onMessage = (msg) => {
setWebviewHeight(parseInt(msg.nativeEvent.data))
}
4、webview的设置,在source中,除了设置html内容content外,还给它加了个强制改样式的css
<WebView
style={{width: '100%', height: webviewHeight, backgroundColor:'transparent'}}
javaScriptEnabled={true}
source={{html: `<style>*{color:#fff !important;}</style>${content}`}}
injectedJavaScript={INJECTEDJAVASCRIPT}
scalesPageToFit={false}
onMessage={onMessage}
/>
至此,完美解决!