javascript - How can I send a data to webview by clicking on react native button
问题描述
I have used the componentDidMount method which sending data properly to webview but i want to send data webview when I click on particular react native button.
In this webview is displaying the local html page and in this I'm sending the data to webview and on load event in html page alert the data which sent by react native in this componentdidmount method is succesfully sending data to webview html page but when I'm trying same code in method which saying that this.input
is undefined.
export default class HtmlRender extends Component {
//error:this.input is undefined
sendData() {
this.input.postMessage( data )
}
// This Is working
componentDidMount(){
this.input.postMessage( data)
}
render(){
return (
<View style={styles.fullContainer}>
<View style={styles.webviewBorder} >
<WebView
ref={(input) => this.input = input}
source={{uri:'file:///android_asset/Page.html'}}
/>
</View>
<View >
<Button onPress={this.sendData}>
<Text>
Data
</Text>
</Button>
</View>
</View >
)}
解决方案
你可以用注入的JavaScript 来做到这一点。只需在 const 中定义您的 html 页面源
const htmlData = require('./page.html');
并创建如下方法
injectedToHtml() {
const myData = {planet: 'earth', galaxy: 'milkyway'};
let injectedData = `document.getElementById('container').value = '${myData.planet+myData.galaxy}';`;
return injectedData;
}
并在您的组件中像这样返回您的网络视图
<WebView
source={htmlData}
javaScriptEnabled={true}
injectedJavaScript={injectedToHtml()}
style={{flex: 1}}
/>
而已!如果您还有任何问题,请告诉我。
你的 html 文件看起来像这样..
<!DOCTYPE html>
<html>
<head>
<style>
#container {
width:100%;
height:100vh;
display: flex;
align-items:center;
justify-content: center;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
推荐阅读
- excel - CSV 数据导入后无法在 Excel 中绘图(所有值 = 0)
- xslt - 如何在另一个节点中声明一个将属性绑定到另一个属性的变量?
- javascript - 如何填充画布并添加文本
- javascript - 异步函数未捕获(承诺中)未定义错误
- python - 如何在熊猫 groupby 中组合连接的字符串
- c# - 如何使用 |数据目录| 用asp.net核心替换appsettings.json中的字符串?
- legend - Vega 图例和每标记颜色
- email - 电子邮件 IDNA 编码。我们是否需要对整个电子邮件或每个部分分别进行编码?
- jquery-ui - 加载资产的顺序不符合资产文件
- angular - 当 mat-tab 处于活动状态时启动角度动画