3 回答
TA贡献1815条经验 获得超6个赞
JSbin 示例使用了一个on("draw")不受支持的自定义函数react-chartist(并且它还手动计算标签位置,因此如果系列中的宽度或数据量发生变化,它将不会缩放)。也就是说,最简单的解决方案是创建您自己的Chartist实例并对其进行更改以满足您的需求。
工作示例(无论 中的宽度和/或项目数量如何,标签和图像都将缩放到中心series):
组件/图表
import React, { Component, cloneElement, Children } from "react";
import Chartist from "chartist";
import PropTypes from "prop-types";
class Chart extends Component {
componentDidUpdate(prevProps) {
if (this.props !== prevProps) this.updateChart(this.props);
}
componentWillUnmount() {
if (this.chart) {
try {
this.chart.detach();
} catch (err) {
throw new Error("Internal chartist error", err);
}
}
}
componentDidMount = () => this.updateChart(this.props);
updateChart = ({ data, listener, options, responsiveOptions, type }) => {
let event;
if (this.chartist) {
this.chart.update(data, options, responsiveOptions);
} else {
this.chart = new Chartist[type](
this.chart,
data,
options || {},
responsiveOptions || []
).on("draw", context => {
if (type === "Pie") return;
if (context.type === "label" && context.axis.units.pos === "x") {
if (context && context.text) {
const group = new Chartist.Svg("g");
const isBar = type === "Bar";
const hasImage = context.text.image;
const hasLabel = context.text.label;
if (hasImage) {
const x = isBar
? context.x + context.width / 2 - 15
: context.x + 5;
const y = isBar
? context.y + context.height / 2 - 10
: context.y + 0;
group.append(
new Chartist.Svg("image", {
"xlink:href": context.text.image,
width: "30px",
height: "30px",
x,
y
})
);
}
if (hasLabel) {
const x = isBar
? context.x + context.width / 2 + 5
: context.x + 30;
const y = hasImage
? context.y + context.height / 2 + 30
: context.y + context.height / 2;
group.append(
new Chartist.Svg("text", {
width: "100px",
height: "40px",
x,
y,
"text-anchor": "middle",
"alignment-baseline": "hanging"
}).text(context.text.label || "")
);
}
context.element.replace(group);
}
}
});
if (listener) {
for (event in listener) {
if (listener.hasOwnProperty(event)) {
this.chart.on(event, listener[event]);
}
}
}
}
return this.chart;
};
render = () => {
const { className, style, children, data, type } = this.props;
const childrenWithProps =
children &&
Children.map(children, child =>
cloneElement(child, {
type,
data
})
);
return (
<div
className={`ct-chart ${className || ""}`}
ref={ref => (this.chart = ref)}
style={style}
>
{childrenWithProps}
</div>
);
};
}
Chart.propTypes = {
type: PropTypes.oneOf(["Line", "Bar", "Pie"]).isRequired,
data: PropTypes.object.isRequired,
className: PropTypes.string,
options: PropTypes.object,
responsiveOptions: PropTypes.array,
style: PropTypes.object
};
export default Chart;
添加回答
举报
