反应中 ChartJS 中条形图上的超链接

Hyperlink on bars in ChartJS in react

我在 React 功能组件中使用 chartjs-2(请在此处找到代码:https://codesandbox.io/s/elastic-brook-okkce?file=/src/Dashboard.jsx

我在这里渲染了 4 个条,我想为每个条上的 onClick 事件定义一个特定的处理函数。 就像条形标签中有 4 种类型,点击每个条形图我想显示特定于所点击条形图类型的内容。 如何实现?

function Dashboard(props) {
  const classes = useStyles();
  const [data, setdata] = React.useState({
    labels: ["type1", "type2", "type3", "type4"],
    datasets: [
      {
        label: "text that comes on hover", 
        backgroundColor: [
          //................................................colors of the bars............
          "#3e95cd",
          "#8e5ea2",
          "#3cba9f",
          "#e8c3b9",
          "#c45850"
        ],
        barThickness: 80,
        data: [50, 100, 75, 20, 0] //......................values for each bar...........
      }
    ]
  });

  const getChartData = canvas => {
    return data;
  };
  return (
    <React.Fragment>
      <div
        className={classes.chart}
        style={{ position: "relative", width: 900, height: 450 }}
      >
        <Bar
          options={{
            responsive: true,
            maintainAspectRatio: true,
            legend: { display: false },
            title: {
              display: true,
              text: "Title for the graph"
            }
          }}
          data={getChartData}
        />
      </div>
    </React.Fragment>
  );
}

export default Dashboard;

您可以使用 onElementsClick。请检查以下代码:

<Bar
    options={{
        responsive: true,
        maintainAspectRatio: true,
        legend: {display: false},
        title: {
            display: true,
            text: "Title for the graph"
        }
    }}
    onElementsClick={(e) => {
        console.log(e, 'e')
    }}
    data={getChartData}
/>