You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React函数式组件中输入变化时更新Highcharts柱状图方法

React函数式组件实现输入框联动更新Highcharts柱状图

下面是适配highcharts-react-official@3.2.0的完整代码片段,实现输入框内容修改时实时更新柱状图:

import React, { useState } from 'react';
import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';

const BarChartForm = () => {
  // 初始化5个输入框对应的柱状图数据,默认值可按需调整
  const [dataPoints, setDataPoints] = useState([10, 20, 30, 40, 50]);

  // 处理输入框变化,更新对应位置的数据
  const handleInputChange = (index, value) => {
    // 将输入值转为数字,非数字则设为0
    const numValue = isNaN(Number(value)) ? 0 : Number(value);
    const newData = [...dataPoints];
    newData[index] = numValue;
    setDataPoints(newData);
  };

  // 构建Highcharts配置项
  const chartOptions = {
    chart: {
      type: 'column'
    },
    title: {
      text: '输入框联动柱状图'
    },
    xAxis: {
      categories: ['项1', '项2', '项3', '项4', '项5'], // 对应5个输入框的分类
      crosshair: true
    },
    yAxis: {
      min: 0,
      title: {
        text: '数值'
      }
    },
    series: [{
      name: '数据',
      data: dataPoints // 绑定状态中的数据
    }]
  };

  return (
    <div style={{ padding: '20px' }}>
      {/* 5个输入框,对应柱状图的5个数据点 */}
      <div style={{ marginBottom: '20px', display: 'flex', gap: '10px' }}>
        {dataPoints.map((value, index) => (
          <input
            key={index}
            type="number"
            value={value}
            onChange={(e) => handleInputChange(index, e.target.value)}
            style={{ width: '80px', padding: '8px' }}
            placeholder={`项${index+1}`}
          />
        ))}
      </div>
      {/* Highcharts组件 */}
      <HighchartsReact
        highcharts={Highcharts}
        options={chartOptions}
      />
    </div>
  );
};

export default BarChartForm;

关键说明:

  • 用useState维护5个数据点的状态,输入框修改时触发组件重渲染
  • handleInputChange函数负责将输入值转为数字并更新对应位置的数组元素,避免直接修改原状态
  • Highcharts配置项的series[0].data直接绑定dataPoints状态,状态更新时图表会自动重新渲染
  • 输入框通过map循环生成,与x轴分类一一对应,保持结构统一

内容的提问来源于stack exchange,提问作者user3342682

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 12:47:03