首页 > 解决方案 > React Vis 水平十字准线

问题描述

有没有办法显示十字准线,使其水平而不是垂直?默认情况下,给定一个点列表,它将垂直十字准线捕捉到最近点的 x 值。

标签: reactjsreact-vis

解决方案


我能够创建一个自定义的 Crosshair 组件,该解决方案有点骇人听闻,因为我使用的是库未公开的实用程序,如果您升级版本,您需要小心。你可以在这里查看https://codesandbox.io/s/react-vis-forked-t8hvz?file=/src/Horizo​​ntalCrosshair.js

与原始组件的重要区别是:

从库中获取导入

    import { ScaleUtils } from "react-vis";
    import { transformValueToString } from "react-vis/dist/utils/data-utils"; // hackish

更改道具类型以获得正确的边距并更改方向值

      marginRight: PropTypes.number,
      orientation: PropTypes.oneOf(["top", "bottom"]),

更改计算以找到顶部位置而不是左侧

    const y = ScaleUtils.getAttributeFunctor(this.props, "y");
    const innerTop = y(value);

    const {
      orientation = innerTop > innerHeight / 2 ? "top" : "bottom"
    } = this.props;
    const right = marginRight;
    const top = marginTop + innerTop;
    const innerClassName = `rv-crosshair__inner rv-crosshair__inner--${orientation}`;

最后设置顶部和宽度而不是左侧和高度

      <div
        className={"rv-crosshair horizontal"}
        style={{
          top: `${top}px`,
          right: `${right}px`
        }}
      >
        <div
          className="rv-crosshair__line"
          style={{ width: `${innerWidth}px`, ...style.line }}
        />

并添加一些 CSS 类以正确定位组件

样式.css

.rv-crosshair.horizontal .rv-crosshair__line {
  height: 1px;
}

.rv-crosshair__inner {
  right: 0;
}

.rv-crosshair__inner--bottom {
  top: 4px !important;
}

.rv-crosshair__inner--top {
  bottom: 4px !important;
  top: unset;
}


推荐阅读