问题描述
我正在努力解决这个问题。如何使用 CSS 有条件地呈现图表图表的线条颜色,具体取决于 Y 的第一个值是小于还是大于数据系列中 Y 的最后一个值?
内联样式类似于:
style={{ series[0] < series[-1] ? "red" : "green" }}
according to the docs,ChartistGraph 组件使用了一个用于内联 css 样式的样式属性,但是我无法使其正常工作。
<ChartistGraph data={data} options={options} type={type} style={style} />
https://codesandbox.io/s/objective-ramanujan-35cij
感谢您的帮助。
编辑:
import React from "react";
import ChartistGraph from "react-chartist";
import "./styles.css";
export function MiniGraphs(props)
{
const { historicalPrice,daterange,symbol } = props;
const filterBySymbol = (symbol,key) =>
historicalPrice
.filter((elm) => elm.symbol === symbol)
.map((elm) => elm[key]);
const mapper = {
labels: filterBySymbol(symbol,"date"),series: [filterBySymbol(symbol,"adj_close")]
};
const getChartData = () =>
{
const labels = [];
const series = [];
historicalPrice.slice(-daterange).forEach((item,) =>
{
if (daterange === 5)
{
labels.push(item.date[0]);
series.push(item.close);
}
if (daterange === 30)
{
labels.push(item.date.slice(3,10));
series.push(item.close);
}
if (daterange === 60)
{
labels.push(item.date.slice(3,7));
series.push(item.close);
}
if (daterange === 253)
{
labels.push(item.date.slice(3,7));
series.push(item.close);
}
});
return {
labels: labels,series: [series]
};
};
// Add graph configuration here
const chartOptions = {
showGrid: false,chartPadding: 15,showGridBackground: false,// width: 2000,height: "150",labelOffset: 200,// scaleMinSpace: 20
onlyInteger: true,showPoint: false,showArea: true,axisX: {
labelInterpolationFnc: function (value,index)
{
if (daterange === 5)
{
return index % 1 === 0 ? value : null;
}
if (daterange === 30)
{
return index % 15 === 0 ? value : null;
}
if (daterange === 60)
{
return index % 20 === 0 ? value : null;
}
if (daterange === 253)
{
return index % 60 === 0 ? value : null;
}
},}
};
// Get all values
const all = mapper.series[0];
// Get first + last
const first = all[0];
const last = all[all.length - 1];
// Get className
const lineColor = first > last ? "red" : "green";
return (
<>
{ historicalPrice && (
<ChartistGraph
className={"line-" + lineColor}
data={getChartData()}
options={chartOptions}
type="Line"
/>
)}
</>
);
}
<MiniGraphs
historicalPrice={historicalPrice.filter(
(i) => i.symbol === data.symbol
)}
daterange={date}
symbol={data.symbol}
/>
.line-red .ct-line {
stroke: red !important;
}
.line-green .ct-line {
stroke: green !important;
}
解决方法
在 MiniGraphs
组件中,您可以获得所需的值,并使用 className 更改所需的线条颜色,如下所示:
// Get all values
const all = mapper.series[0];
// Get first + last
const first = all[0];
const last = all[all.length - 1];
// Get className
const lineColor = first > last ? "red" : "green";
// Render
return (
<>
{
historicalPrice && (
<ChartistGraph
className={"line-" + lineColor} // <-- Add className
data={mapper}
options={chartOptions}
type="Line"
/>
)
}
</>
)
然后,使用一些简单的 css 您可以像这样更改线条颜色:\
.line-red .ct-line {
stroke: red !important;
}
.line-green .ct-line {
stroke: green !important;
}
不要忘记包含样式文件:import './styles.css';