【发布时间】:2019-05-31 04:18:23
【问题描述】:
我收到此错误: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>
);
}
}
为什么会出现这样的错误?提前感谢您的帮助:)
【问题讨论】:
标签: reactjs