我得到这个错误: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>
);
}
}
为什么会有这样的错误呢?提前感谢您的帮助:)
发布于 2019-01-04 23:29:41
我注意到你的代码,你在componentDidMount中使用了箭头函数。
它应该是:
componentDidMount() {}
同样,如果你在handleScroll中使用箭头函数,那么就不需要在构造函数中绑定,试着移除它,然后修改handleScroll,如下所示:
handleScroll = () => {
const { isActive } = this.state;
if (this.wrapRef) {
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 });
}
}
}
另外,在componentDidMount中删除事件侦听器之后的函数调用this.handleScroll(),因为它没有任何用处。
发布于 2019-01-04 23:21:53
我认为问题在于您还没有为wrapRef
创建任何ref
。如错误所示,无法获取null的属性;因此wrapRef
本身为null
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>
);
}
}
https://stackoverflow.com/questions/54041548
复制相似问题