使用ResponsiveContainer和引入resize触发器。
具体的解决代码如下:
import React from "react";
import { LineChart, Line, ResponsiveContainer } from "recharts";
class MyChart extends React.Component {
state = {
width: 0,
height: 0
};
handleResize = () => {
this.setState({
width: this.chart.offsetWidth,
height: this.chart.offsetHeight
});
};
componentDidMount() {
window.addEventListener("resize", this.handleResize);
this.setState({
width: this.chart.offsetWidth,
height: this.chart.offsetHeight
});
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
render() {
const { data } = this.props;
return (
(this.chart = el)}>
);
}
}
export default MyChart;
这段代码首先使用了window的resize事件来触发handleResize方法,可以在组件挂载、卸载和重新渲染时正确地随窗口大小改变来更新。在一个div元素中嵌套Recharts的ResponsiveContainer组件和LineChart组件,可以让图表很好地适应各种屏幕大小。使用activeDot={{ r: 8 }}属性来指定图表上的活动点半径大小,从而达到调整图表大小不会改变活动点大小的效果。