我正在尝试创建一个带有输入字段的 Highcharts 图表,允许用户自定义自己的颜色首选项。不过,我对使用 React JS 还比较陌生。我正在传递输入字段中的值并将它们附加到图表选项中,并希望在单击提交按钮时更新图表。我尝试过使用 React api 中的 setState() 和 redraw() 但我没有运气。我在浏览器上运行时遇到此错误:
Uncaught TypeError: Cannot read property 'setState' of undefined
at HTMLButtonElement.<anonymous> (VM111:125)
at HTMLButtonElement.dispatch (jquery.min.js:3)
at HTMLButtonElement.q.handle (jquery.min.js:3)
(anonymous) @ VM111:125
dispatch @ jquery.min.js:3
q.handle @ jquery.min.js:3
任何帮助将不胜感激,谢谢!
$('#submit').click(function () {
this.chart.setState(function () {
return {
chart:{
backgroundColor: '' + $('#backgroundColorSetting').val() //sets chart background
},
series: [{
color: '' + $('#colorSetting').val(), //sets the color of Line
name: $('#xaxis').val() //sets name of X-Axis
}],
yAxis:{
text: $('#yaxis').val() //sets name of Y-Axis
}
}
});
});
var Chart = React.createClass({
componentDidMount: function() {
if (this.props.modules) {
this.props.modules.forEach(function(module) {
module(Highcharts);
});
}
this.chart = new Highcharts[this.props.type || "Chart"](
this.props.container,
this.props.options
);
},
componentWillUnmount: function() {
this.chart.destroy();
},
render: function() {
return React.createElement('div', {
id: this.props.container
});
}
}),
categories= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
data= [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
element = React.createElement(Chart, {
container: 'chart',
options: {
title: {
text: 'Inverted Chart'
},
chart: {
inverted: true,
polar: false
},
subtitle: {
text: 'Subtitle1'
},
xAxis: {
categories: categories
},
series: [{
type: 'line',
colorByPoint: true,
data: data,
lineColor:'#f7eac8'
//showInLegend: false
}]
}
});
ReactDOM.render(element, document.getElementById('react-inverted'));
最佳答案
如果使用 React,则无需使用 jQuery。表单可以使用 React 组件来处理。我建议阅读 forms (尤其是受控组件)在 React 文档中。我将使用不受控制的组件。
更改渲染方法以渲染形式:
render: function() {
return React.createElement('div', null,
React.createElement('div', {
id: this.props.container
}),
React.createElement('form', {
onSubmit: this.onSubmit
},
React.createElement('input', {
ref: input => this.colorInput = input,
placeholder: 'Type red, black or blue'
}),
React.createElement('input', {
type: 'submit'
})
)
);
}
并定义一个提交处理程序,它将通过 Axis.update() 更新轴
onSubmit: function(e) {
e.preventDefault();
var color = this.colorInput.value;
if (['red', 'black', 'blue'].includes(color)) {
this.chart.xAxis[0].update({
lineColor: color
});
}
},
关于javascript - 如何通过输入字段使用 React JS 更新 Highcharts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42767264/