反应功能未激活

时间:2019-07-29 13:08:39

标签: reactjs

在React中,我有window.onscroll函数,当向下滚动时应激活 更改将setState classAnimation设置为“ testing2”的函数。

由于某些原因,更改功能未激活。它给出TypeError:无法读取未定义的属性“更改”。

我的最终目标是将名为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的文本,保密,不动产 用户向下滚动时显示为红色。

2 个答案:

答案 0 :(得分:3)

这里有两个主要问题。

设置myFunction = () => { //your logic } componentDidMount(){ window.addEventListener('scroll', this.myFunction) } componentWillUnmount(){ window.removeEventListener('scroll', this.myFunction) } 事件应如下所示:

bind

您正在绑定箭头函数(此为词法)。使用类方法符号或不带change = () =>{/* Don't bind this */} change(){/* Should be binded in `constructor` */} 的箭头函数:

dos2unix file1 file2 file3 fileN

答案 1 :(得分:0)

您丢失了<input type="date" name="dateBegin"> <div id="debug"></div>对象的上下文。在

之内
this

您拥有新的范围,因此function myFunction() {} 失去了它的上下文。您需要将myFunction放置为方法,并将其绑定到构造函数中的作用域。

您目前的解决方案有this调用myFunction(),这意味着编译器正在this.change中寻找change,这显然不是代码的结构。< / p>

类似的事情将为您服务:

myFunction()