如何让React Chartjs随窗口缩小而自动调整大小

7
我有这段代码,但不知何故,当我调整窗口大小时,它会变大,但不会缩小。请问如何解决这个问题。 https://codesandbox.io/s/react-chartjs-2-example-1nur4
import React from "react";
import { render } from "react-dom";
import LineDemo from "./LineDemo";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};

const App = () => (
  <div style={styles}>
    <table style={{ width: "100vw", borderCollapse: "collapse" }}>
      <tbody>
        {Array.from({ length: 4 }, el => "foo")
          .concat(<LineDemo />)
          .map(el => (
            <td style={{ border: "solid" }}>{el}</td>
          ))}
      </tbody>
    </table>
  </div>
);

render(<App />, document.getElementById("root"));
2个回答

9
请查看https://www.chartjs.org/docs/latest/configuration/responsive.html,其中的Important Note部分提到了如何实现响应式。它指出:

Chart.js使用其父容器来更新画布的渲染和显示大小。然而,这种方法要求容器相对定位并且仅用于图表画布。只有设置容器大小的相对值才能实现响应式。

在您的情况下,线状图的父容器是<div>元素。然后可以修改LineDemo.js文件中的LineDemo组件的render函数,使其如下所示:

render() {
  return (
    <div style={{ position: "relative", margin: "auto", width: "80vw" }}>
      <h2>Line Example</h2>
      <Line ref="chart" data={data} />
    </div>
  );
}

这是一个可用的示例:https://codesandbox.io/s/react-chartjs-2-example-hzygw,涉及到IT技术。请注意,保留了HTML标签。

1
对于未来的开发人员,该文档页面已移至此处:https://www.chartjs.org/docs/latest/configuration/responsive.html - myahl
谢谢,@myahl!我已经用新的页面链接更新了答案。 - Rounak

7

对我有效的是为图表容器添加宽度样式:

<div style={{width: '99%'}}>
    <Bar options={options} data={data} />
</div>

然而,如果我将宽度设置为100%,它就无法工作,哈哈。


1
非常奇怪,但对我也解决了。 - Exchange_programming
救命稻草,我花了2个小时在这上面。 - Harry Riley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接