将HTML或图像放入xAxis

时间:2018-08-11 19:15:00

标签: reactjs victory-charts

有没有一种方法可以在简单条形图的xAxis中显示图像?

这是我到目前为止尝试过的:

我正在尝试使用自定义组件覆盖 VictoryAxis tickLabelComponent 中显示的内容。

       <VictoryAxis
            // tickValues specifies both the number of ticks and where
            // they are placed on the axis
            tickValues={props.xTickValues}
            tickFormat={props.xTickFormat}
            // ChartBarCustomLabel is the name of my custom component
            tickLabelComponent={<ChartBarCustomLabel xAxisInformation={props.xAxisInformation} />}
        />

自定义组件在道具 xAxisInformation 中接收图像数组。

这里是:

const ChartBarCustomLabel = (props) => {

return (
    <div>
        <img src={props.xAxisInformation[props.index].icon} alt="" key={props.xAxisInformation[props.index].id}/>
    </div>
);

};

在自定义组件中,我尝试使用 index 获取图标,该索引是为 tickLabelComponent 提供的道具。但是什么也没显示。

实际上,如果我使用React Developer Tools检查代码,图像就在那里...

enter image description here

...但是什么也没呈现。

enter image description here

我认为html或图像无法显示在 tickLabelComponent 中,我应该改用另一个Victory组件。但是哪一个是正确的?

或者也许还有另一种方法可以实现这一目标。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

事实证明,Victory将其数据组件和标签组件呈现在svg标签内。因此,如果我想使用非svg元素,则需要将它们包装在<foreignObject>

唯一的缺点是某些浏览器不支持foreignObject,我需要提供位置。

无论如何,自定义组件现在是这样的:

const ChartBarCustomLabel = (props) => {
    return (
        <foreignObject style={{ paddingTop: String(props.xAxisImagesTopPadding) + "px", paddingLeft: String(props.xAxisImagesLeftInitialPadding + (props.xAxisImagesTickSize * props.index)) + "px" }}>
            {
                props.xAxisInformation[props.index] !== undefined ?
                    <img style={{ minHeight: String(props.xAxisImagesMinHeight) + "px", minWidth: String(props.xAxisImagesMinWidth) + "px" }} src={props.xAxisInformation[props.index].icon} alt="" key={props.xAxisInformation[props.index].id} />
                    : null
            }
        </foreignObject>
    );
};

工作正常!

相关问题