0

我正在渲染 svg 折线,

const SVG = () => {
  const svgRef = React.createRef<SVGSVGElement>();
  const [tooltipIndex, setTooltipIndex] = React.useState(-1);
  const onTouch = (e: React.TouchEvent) => {
    setTooltipIndex(tooltipIndex + 1);
  };

  const PolyLine = () => {
    return <polyline className="ctLine" points="200,100 100,150 200,250" />;
  };
  return (
    <svg
      width="200"
      height="300"
      viewBox="0 0 200 300"
      ref={svgRef}
      onTouchStart={(e) => onTouch(e)}
    >
      <polyline className="ctLine" points="100,50 60,90 30,60" />;
      <PolyLine />
    </svg>
  );
};

课程是这样的:

.ctLine {
  stroke: #0074d9;
  stroke-width: 1px;
  fill: none;
  stroke-dasharray: 1000;
  animation-name: ctLineShow;
  animation-duration: 4s;
  animation-iteration-count: 1;
}

@keyframes ctLineShow {
  0% { stroke-dashoffset: 1000; }
  100% { stroke-dashoffset: 0; }
}

来源在这里https://codepen.io/rogerdehe/pen/dyYEVoQ

我发现功能组件PolyLine差异来自polylinePolyLine每次状态更改时都会动画,而polyline不会?

我的问题是:

  1. 为什么
  2. 我可以修复PolyLinepolyline吗?
4

1 回答 1

1

首先 - 你是对的。React 组件将在 props/state 更改时呈现 - 这是预期的行为。

其次 - 你把你的PolyLine组件放在里面SVG。当您调用它时,它会在每个渲染setTooltipIndex上创建新的上下文。onTouchStart移出PolyLineSVG防止不必要的渲染。

 const PolyLine = () => {
    console.log('render');
    return <polyline className="ctLine" points="200,100 100,150 200,250" />;
  };

const SVG = () => {
  const svgRef = React.createRef<SVGSVGElement>();
  const [tooltipIndex, setTooltipIndex] = React.useState(-1);
  const onTouch = (e: React.TouchEvent) => {
    setTooltipIndex(tooltipIndex + 1);
....
于 2020-05-27T08:35:21.787 回答