支援android&ios高度自適應及JS相互呼叫的元件react-native-webview2
阿新 • • 發佈:2019-02-13
本專案是WebView 或 Web 元件,支援Android、iOS, 支援auto height高度自適應及在html頁面和RN元件之間call js相互呼叫js方法,very useful & easily!
基於React-native原生的WebView元件純js實現, 起名為react-native-webview2 或 WebView 或 Web.
- react-native-webview2 當你設定了屬性 source={uri:xxx}時可以動態改變WebView 的高度(目前還不支援source={html}),但若你設定了屬性style={height:xxx}設定了高度就不能自適應了, 設定了高度後高度是固定的.
- react-native-webview2 也可以讓你在html頁面和reactnative之間相互呼叫js程式碼。要從rn元件呼叫html頁面的js,你只需要在rn元件中呼叫this.web.evalJs("js code...here") ,若要呼叫react-native程式碼,你只需要在html頁面中呼叫 returnEval("rn code...here"),同時你需要設定這個元件的屬性evalReturn={(r) => {eval(r)}.
- react-native-webview2支援所有其他原生React Native WebView的屬性.
WebView示例
WebView 使用方法
- 執行 npm install react-native-webview2 --save
-
編寫程式碼:
import Web from 'react-native-webview2'; <Web ref={(c) => {this.web = c}} evalReturn={(r) => {eval(r)} source={{uri: 'xxx'}} style={[styles.web, {minHeight: 300}]} ...other props />
WebView 配置
新增的屬性
- evalJs: 從react-native呼叫html頁面裡的js的方法. 例如: this.web.evalJs('var t = document.title; alert(t)');
- evalReturn: 若你需要從html頁面呼叫react-native的方法,這個屬性是需要的. 固定寫法:evalReturn={(r) => {eval(r)}.
- go: 開啟一個新的url. 例如: this.web.go('http://xxxxxx');
其他
- returnEval: 在html頁面的一個function,從html頁面呼叫react-native的方法時呼叫的js方法, 例如:returnEval('this.setText("from html page...")')
Licensed
MIT License