问题描述
我想在react(recharts)中有一个图表组件,当我使用map函数将我的属性数组映射到带有该道具的条形时,问题是它在我的图表中没有显示条形! 这是我的代码:
export const HorizontalBarChart = (props: {
data: Array<any>,properties: Array<any>,}) => {
const barItems = props.properties.map((obj) => {
<Bar dataKey={obj.key}
fill={obj.color}
radius={[0,10,0]}
>
</Bar>
});
return (
<BarChart
width={450}
height={250}
data={props.data}
layout="vertical"
margin={{
top: 5,right: 30,left: 20,bottom: 5,}}
>
{barItems}
<Cartesiangrid horizontal={false} />
<XAxis
type="number"
reversed={true}
domain={[0,MAX]}
//hide={true}
/>
<YAxis type="category"
dataKey="name"
orientation="right"
hide={true}
/>
</BarChart>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
但是当我手动实现条形码时,它可以工作!像这样:
export const HorizontalBarChart = (props: {
data: Array<any>,}) => {
return (
<BarChart
width={450}
height={250}
data={props.data}
layout="vertical"
margin={{
top: 5,}}
>
<Bar dataKey={props.properties[1].key}
fill={props.properties[1].color}
radius={[0,0]}
>
</Bar>
<Bar dataKey={props.properties[2].key}
fill={props.properties[2].color}
radius={[0,0]}
>
</Bar>
{barItems}
<Cartesiangrid horizontal={false} />
<XAxis
type="number"
reversed={true}
domain={[0,MAX]}
//hide={true}
/>
<YAxis type="category"
dataKey="name"
orientation="right"
hide={true}
/>
</BarChart>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
如果您能帮助我解决图表中的问题,我会很高兴。
解决方法
根据您当前的代码,barItems函数存在一个小问题
const barItems = props.properties.map((obj) => {
<Bar dataKey={obj.key}
fill={obj.color}
radius={[0,10,0]}
>
</Bar>
});
如您所见,您忘记了返回Bar组件,因此它什么也不返回
尝试一下
const barItems = props.properties.map((obj) => {
return (<Bar dataKey={obj.key}
fill={obj.color}
radius={[0,0]}
>
</Bar>)
});
或使用粗箭头
const barItems = props.properties.map((obj) =>
<Bar dataKey={obj.key}
fill={obj.color}
radius={[0,0]}
>
</Bar>
);