无法读取 null 属性“getBoundingClientRect”

Eld*_*der 7 reactjs

我收到此错误:Cannot read property 'getBoundingClientRect' of null。我使用这个功能getBoundingClientRect,是因为在我的项目中我想要达到以下效果:当一个元素突出显示时,其余元素具有不同的样式。该消息显示了功能handleScroll。我使用的组件看起来像这样

class QuestionListItem extends Component {
  constructor() {
    super();
    this.state = {
      isActive: false,
    };

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

  componentDidMount = () => {
    window.addEventListener('scroll', this.handleScroll);
    this.handleScroll();
  };

  handleScroll = () => {
    const { isActive } = this.state;
    const { top } = this.wrapRef.getBoundingClientRect();
    if (top > 60 && top < 400 && !isActive) {
      this.setState({ isActive: true });
    }
    if ((top <= 60 || top >= 400) && isActive) {
      this.setState({ isActive: false });
    }
  }

  setWrapRef = (ref) => {
    this.wrapRef = ref;
  }

  render() {
    const { isActive } = this.state;
    const { question } = this.props;
    return (
      <div
        className={`Test__questions-item--noactive ${isActive && 'Test__questions-item--active'}`}
        ref={this.setWrapRef}
      >
        <li key={question.id}>
          <p>
            {question.question}
          </p>
          <QuestionAnswerForm name={question.question} />
        </li>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么会出现这样的错误呢?我在这里先向您的帮助表示感谢 :)

Ami*_*avi 0

我认为问题是你还没有refwrapRef. 正如错误所说无法获取 null 的属性;所以它wrapRef本身是空的

class QuestionListItem extends Component {
  constructor() {
    super();
    this.state = {
      isActive: false,
    };

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

  componentDidMount = () => {
    window.addEventListener('scroll', this.handleScroll);
    this.handleScroll();
  };

  wrapRef=React.createRef();

  handleScroll = () => {
    const { isActive } = this.state;
    const { top } = this.wrapRef.current.style;
    if (top > 60 && top < 400 && !isActive) {
      this.setState({ isActive: true });
    }
    if ((top <= 60 || top >= 400) && isActive) {
      this.setState({ isActive: false });
    }
  }

  render() {
    const { isActive } = this.state;
    const { question } = this.props;
    return (
      <div
        className={`Test__questions-item--noactive ${isActive && 'Test__questions-item--active'}`}
        ref={this.wrapRef}
      >
        <li key={question.id}>
          <p>
            {question.question}
          </p>
          <QuestionAnswerForm name={question.question} />
        </li>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)