Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法读取属性';风格';反应中的空值_Javascript_Reactjs_React Native - Fatal编程技术网

Javascript 无法读取属性';风格';反应中的空值

Javascript 无法读取属性';风格';反应中的空值,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我想让这一切顺利。工作也是一样,但这不起作用。 看看这个 如您所见,backgroundScroll正常工作, 但是过了一会儿,我添加了sth,它不工作。下面是错误消息。 未捕获的TypeError:无法读取null的属性“style” 评估时 import React,{createRef,PureComponent}来自“React”; 类历史扩展了PureComponent{ backgroundScroll=createRef() sth=createRef()//错误 handelS

我想让这一切顺利。工作也是一样,但这不起作用。
看看这个
如您所见,
backgroundScroll
正常工作,
但是过了一会儿,我添加了
sth
,它不工作。下面是错误消息。
未捕获的TypeError:无法读取null的属性“style” 评估时

import React,{createRef,PureComponent}来自“React”;
类历史扩展了PureComponent{
backgroundScroll=createRef()
sth=createRef()//错误
handelScroll=()=>{
让scrollTop=document.body.scrollTop
this.backgroundScroll.current.style.backgroundPositionY=`${scrollTop/3}px`
}
单击右=()=>{
此.sth.current.style.animation='opacityChange 2s'
}
componentDidMount(){
window.addEventListener('scroll',this.handelScroll);
}
组件将卸载(){
window.removeEventListener('scroll',this.handelScroll);
}
render(){
返回(
{this.state.picture&&
}
)
}
}

导出默认历史记录
我觉得这里缺少一些代码,因为您在render方法中引用了this.state.picture。我猜clickRight方法在不引用dom元素时尝试访问sth.style属性(即,如果this.state.picture不存在,则包含sth ref的div将不会被渲染)

首先,我将把ref的创建移到构造函数:

class History extends PureComponent {
constructor() {
    super();
    this.backgroundScroll = createRef();
    this.sth = createRef();
    }
}

然后尝试删除条件渲染,看看它是否有效。

构造函数的目的不是解决问题,而是从现在起将引用放在其中的最佳实践,如我在前面的评论中所示

在您的
单击右键
-方法中尝试此操作:

clickRight = () => {
    if(this.state.picture) {
        this.sth.current.style.animation='opacityChange 2s'
    }
}

您确定this.sth具有当前属性吗?console.log它以确保我不知道当前的确切内容,但它与
backgroundScroll=createRef()一起工作
,因此我也将此语句用于
sth
。我认为此问题与&&条件语句有关,但不确定。实际上,构造函数没有帮助,但如果没有条件语句,它可以工作。实际问题是条件渲染,那么我该如何处理?