【问题标题】:How to create a new ref for each component instance如何为每个组件实例创建一个新的 ref
【发布时间】:2019-01-14 11:10:05
【问题描述】:

如何为组件的每个实例创建一个引用

我已经将一些代码提取到它自己的组件中。该组件是一个 PlayWhenVisible 动画组件,它根据元素是否在视图中来播放/停止动画。

我在组件构造函数中创建了一个引用,但是由于在使用组件的 2 个实例时出现了一些延迟,我想知道是否应该在组件外部创建引用并将它们作为道具传递,或者是否有一种为每个组件实例创建新实例的方法。

import VisibilitySensor from "react-visibility-sensor";
class PlayWhenVisible extends React.Component {
  constructor(props) {
    super(props);
    this.animation = React.createRef();
    this.anim = null;
  }
render() {
    return (
      <VisibilitySensor
        scrollCheck
        scrollThrottle={100}
        intervalDelay={8000}
        containment={this.props.containment}
        onChange={this.onChange}
        minTopValue={this.props.minTopValue}
        partialVisibility={this.props.partialVisibility}
        offset={this.props.offset}
      >
        {({ isVisible }) => {
          isVisible ? this.anim.play() : this.anim && this.anim.stop();
          return (
            // <div style={style}>
            <i ref={this.animation} id="animation" className={this.props.class} />
          );
        }}
      </VisibilitySensor>
    );
}
}

【问题讨论】:

  • 目前还不清楚问题出在哪里。每个 PlayWhenVisible 实例都有自己的 animation 参考。
  • 能否分享完整代码以便更好地理解?
  • 如果您遇到延迟,并不是因为调用了createRef()
  • @estus 我想知道这两个引用是否会因为它们使用相同的名称而发生冲突,但由于它们是封装的,因此不会有任何原因。

标签: reactjs react-ref


【解决方案1】:

该问题是由 VisibilityChecker 组件引起的,该组件溢出容器并导致其在触发时不稳定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 2022-07-21
    相关资源
    最近更新 更多