我正在尝试在我的webview中使用react-native应用程序呈现Chart.js
图表。
但我无法做postMessage
或渲染画布图。
我认为我在脚本标签中的功能不起作用,有人可以让我知道我做错了什么。
PS:我尝试使用postmessage
中的injectJavascrpt
选项检查至少webview
是否可行,即使我的网页浏览中没有发送任何消息。
这是我为绘制图表而编写的组件代码
import React, { Component } from 'react'
import { WebView, StyleSheet, View } from 'react-native'
class WebViewGraph extends Component {
state = {
init: `
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"/>
</head>
<body>
<div>
<canvas id="chart"></canvas>
<h1>hello</h1>
<p>gyfgyg</p>
</div>
<script>
function abc() {
var ctx = document.getElementById("chart").getContext("2d");
var gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(250,174,50,1)');
gradient.addColorStop(1, 'rgba(250,174,50,0)');
var data = {
labels : ["02:00","04:00","06:00","08:00","10:00","12:00","14:00","16:00","18:00","20:00","22:00","00:00"],
datasets: [
{
fillColor : gradient, // Put the gradient here as a fill color
strokeColor : "#ff6c23",
pointColor : "#fff",
pointStrokeColor : "#ff6c23",
pointHighlightFill: "#fff",
pointHighlightStroke: "#ff6c23",
data : [25.0,32.4,22.2,39.4,34.2,22.0,23.2,24.1,20.0,18.4,19.1,17.4]
}
]
};
var options = {
responsive: true,
datasetStrokeWidth : 3,
pointDotStrokeWidth : 4,
tooltipFillColor: "rgba(0,0,0,0.8)",
tooltipFontStyle: "bold",
tooltipTemplate: "<%if (label){%><%=label + ' hod' %>: <%}%><%= value + '°C' %>",
scaleLabel : "<%= Number(value).toFixed(0).replace('.', ',') + '°C'%>"
};
var myLineChart = new Chart(ctx).Line(data, options);
window.postMessage('Hello there')
}
abc()
</script>
</body>
</html>`
}
onMessage = (data) => {
console.log(data)
}
render() {
const str = `${this.state.init}`
return (
<View style={styles.full}>
<WebView
style={styles.full}
source={{ html: str, baseUrl: 'web/' }}
javaScriptEnabled
domStorageEnabled
scalesPageToFit
scrollEnabled={false}
automaticallyAdjustContentInsets
onMessage={this.onMessage}
/>
</View>
)
}
}
const styles = StyleSheet.create({
full: {
flex: 1,
backgroundColor: '#c3c3c3'
}
})
export default WebViewGraph
任何帮助都将不胜感激。
答案 0 :(得分:0)
您需要使用单独的标记关闭script
标记,即<script src="..."></script>
。愚蠢而真实。从那里开始,如果您与Chart.js
用法相关,则应该开始在JavaScript控制台中看到错误。