Javascript ReactJS-ref返回“返回”;“未定义”;
我将ReactJS与NextJS一起使用。当我试图设置Javascript ReactJS-ref返回“返回”;“未定义”;,javascript,reactjs,position,ref,Javascript,Reactjs,Position,Ref,我将ReactJS与NextJS一起使用。当我试图设置ref时,我的控制台返回我未定义的,这怎么可能?如何解决这个困难?我曾尝试在网上阅读一些观点,但没有成功 这里是我的片段: componentDidMount() { this.myRef = React.createRef(); window.addEventListener('scroll', this.handleScroll, { passive: true }) } co
ref
时,我的控制台返回我未定义的
,这怎么可能?如何解决这个困难?我曾尝试在网上阅读一些观点,但没有成功
这里是我的片段:
componentDidMount() {
this.myRef = React.createRef();
window.addEventListener('scroll', this.handleScroll, { passive: true })
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll)
}
handleScroll(e) {
e.preventDefault();
// let offsetTop = this.myRef.current.offsetTop;
// here I'm trying just a console.log to preview the value
// otherwise my program will just crash
console.log("I'm scrolling, offsetTop: ", this.myRef)
}
render() {
return (
<div className={style.solution_container_layout} >
<div ref={this.myRef} className={style.solution_item}>
componentDidMount(){
this.myRef=React.createRef();
window.addEventListener('scroll',this.handleScroll,{passive:true})
}
组件将卸载(){
window.removeEventListener('scroll',this.handleScroll)
}
handleScroll(东){
e、 预防默认值();
//让offsetTop=this.myRef.current.offsetTop;
//在这里,我只是尝试一个console.log来预览值
//否则我的程序就会崩溃
log(“我正在滚动,偏移:”,this.myRef)
}
render(){
返回(
任何暗示都很好,
谢谢很难从您添加的代码中分辨出来,但您可能只是缺少构造函数中的这一命令:
constructor( props ){
super( props );
this.handleScroll = this.handleScroll.bind(this)
}
更多信息:从
createRef
返回的对象的current
属性在第一次渲染时设置,因此如果在组件渲染后在componentDidMount
中创建该属性,则不会设置该属性
您还必须绑定handleScroll
方法,否则这将不是您所期望的
示例
类应用程序扩展了React.Component{
myRef=React.createRef();
componentDidMount(){
addEventListener(“scroll”,this.handleScroll,{passive:true});
}
组件将卸载(){
window.removeEventListener(“滚动”,this.handleScroll);
}
handleScroll=()=>{
log(“我正在滚动”,this.myRef.current);
};
render(){
还给我;
}
}
ReactDOM.render(,document.getElementById(“根”);
谢谢,但我的元素相对于视口顶部的相对位置(使用scrollTop)似乎保持不变,就像有一个度量值,然后没有其他度量值,你知道可能会发生什么吗please@Webman因为元素不滚动,所以它的scrollpop
不会更改。您可能需要使用'window.pageYOffset'。