React兄弟元素的引用指向同一个元素

问题描述

我正在通过 react-konva 库使用 HTML5 画布。每当我点击画布时,我都会在主组件的状态数组中添加一个点。

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      points: []
    }

    this.handleStageClick = this.handleStageClick.bind(this);
  }

handleStageClick(e) {
    let {x,y} = e.currentTarget.getPointerPosition(); // method from Konva
    this.setState({ points: [ {x,y},...this.state.points ] });
};

render() {
    return (
        <Stage
          width={window.innerWidth * dimensions.canvasWidthMultiplier}
          height={window.innerHeight * dimensions.canvasHeigthMultiplier}
          onClick={this.handleStageClick}
        >
          <Layer>
            {
              this.state.points.map((point,idx) => <Point x={point.x} y={point.y} key={idx} id={idx} />)
            }
          </Layer>
        </Stage>
    );
  }
}

我希望每个点在出现时都具有动画效果,因此我将 react-konva Circle 移动到一个单独的组件,在那里我使用 refs 为 DOM 圆元素分配动画,如 react-konva tutorial 中所述。

class Point extends React.Component {
  constructor(props) {
    super(props);

    this.changeSize = this.changeSize.bind(this);
    this.point = React.createRef();
  }

  changeSize(to) {
    this.point.current.to({
      scaleX: to,scaleY: to,duration: 0.2
    })
  }

  componentDidMount() {
    this.changeSize(6);
  }

  render() {
    let { x,y,id } = this.props;

    return (
      <Circle
        ref={this.point}
        x={x}
        y={y}
        radius={.5}
        fill={colors.point}
        key={id}
      />
    );
  }
}

当我添加第一个点时 - 它按预期制作动画,但是当我添加下一个点时 - 创建动画在第一个点上播放,而不是在创建的点上。

我读过不能在循环中分配 refs,但在我的情况下,我只是在循环中创建了一堆组件,每个组件都有自己的 ref,不要我?

此外,我尝试控制台记录我在 changeSize 方法中分配动画的 ref,结果 ref 指向正确的点,但动画在创建的第一个点上播放。

还有一个最明显的问题:如何让每个新点在创作时制作动画

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)