最近我们的app大改版,相应的就增加了很多新的功能,其中就有h5和react-native 的交互,和webview的高度自适应。现在说一下具体的操作步骤
1.webView的高度自适应。
这个有两种解决方法,第一种是原生的webview,在此基础上计算高度,第二种就是三方插件。
第一种:
1.如果页面直接就是webview显示,可以直接用它。
source={{html: `
${html}`}}
style={{flex:1}}
bounces={false}
scrollEnabled={false}
automaticallyAdjustContentInsets={true}
contentInset={{top:0,left:0}}
onNavigationStateChange={(title)=>{
if(title.title != undefined) {
this.setState({
height:(parseInt(title.title)+20)
})
}
}}>
2.如果页面是listview嵌套webView的,不建议使用,因为我用这个方法写,页面的高度只按照最后一条数据的高度来适配所有的webView的高度,也可能是我写的有问题。
第二种:
三方插件,我试了好几个,感觉 然后就是进行交互了。
不过他源码里面也要改一下,找到他的源码ios 里面的 加上
onMessage = {this.props. onMessage}
/>
renderRow(rowData) {
let html = '
let s = `
function postQuestion() {
var data ={
'id':1,
'name':'zhangsan'
}
window.postMessage(JSON.stringify(data)); //调用rn的接口
}
`
return (
source={{html:html}}
//source={{html:'
onMessage={(e)=>this.onMessage(e)}
customScript={this.state.script}
/>
)
}
onMessage(e) {
alert(1)//应该是我收到的消息
}
这样ios的交互就完成了
ANDROID:
安卓的交互:
安卓源码中的onMessage方法被使用了,看代码:
ref={webview => this.webview = webview}
style={Styles.webView}
javaScriptEnabled={true}
injectedJavaScript={script + customScript}
scrollEnabled={false}
source={webViewSource}
onMessage={this.onMessage}//这个onMessage方法被使用了,那如何交互呢?
messagingEnabled={true}
// below kitkat
onChange={this.onMessage} />
可以在他写的这个this.onMessage方法里面,在最后的位置调用 this.props.onMessage(e);
然后最后的使用方法就和iOS一样了
看一下ios的效果