【发布时间】:2019-07-29 21:35:09
【问题描述】:
在 React 中,我有 window.onscroll 功能,当向下滚动时应该激活 更改将 setState classAnimation 设置为“testing2”的函数。
由于某种原因,更改功能没有激活。它给出了 TypeError: Cannot read property 'change' of undefined。
我的最终目标是将名为 testing2 的类添加到 state 属性并更改 当用户向下滚动超过 50 像素时,屏幕上的文本变为红色。
帮助会很好。
APP.JS
import React, { Component } from 'react';
import './App.css';
import Animations from './components/animations';
class App extends Component {
constructor(props){
super(props);
this.state = {
classAnimation: ''
};
this.change = this.change.bind(this);
}
change = () => {
this.setState({
classAnimation: 'testing2'
});
}
componentDidMount() {
window.onscroll = function() {myFunction()};
function myFunction() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop
> 50) {
this.change();
} else {
}
}
}
render() {
return (
<div className="App">
<Animations testing={this.state.classAnimation}/>
</div>
);
}
}
export default App;
ANIMATION.JS
import React from 'react';
const Home = (props) => {
return(
<div>
<div className={props.testing}>very good test it is</div>
</div>
);
};
export default Home;
APP.CSS
body{
height:1500px;
}
#myP{
position:fixed;
}
.testing2{
position:fixed;
color:red;
}
这就是我得到的:
TypeError:无法读取未定义的属性“更改”
这就是我想要的:
更改名为 Lorem ipsum dolor sit amet, consectetur adipiscing elit 的文本 当用户向下滚动时变为红色。
【问题讨论】:
标签: reactjs