尝试访问event.target。$ something时始终返回“未定义”

时间:2018-08-18 11:39:05

标签: reactjs events scroll event-handling infinite-scroll

我正在尝试为滚动设置事件处理程序, 我在许多资料中都找到了简单的一行:

  

const bottom = e.target.scrollHeight-e.target.scrollTop ===   e.target.clientHeight;

但是由于某种原因,它总是返回undefined:

  handleScroll = (e) => {
    console.log('inside hanglescroll');
    const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
    console.log(e.target.scrollHeight);   **print undefined!!**
    console.log(e.target.scrollTop);     **print undefined!!**
    console.log(e.target.clientHeight);   **print undefined!!**
    if (bottom) {
      console.log('we are in the bottom');
     }
  }


  componentDidMount() {
    window.addEventListener('scroll',this.handleScroll.bind(this));
  }

谢谢!

3 个答案:

答案 0 :(得分:0)

理想情况下,它应该是document而不是e。不需要绑定arrow函数,因为它隐式地绑定了被调用者上下文。

  handleScroll = (e) => {
        let scrollTop = (document.documentElement && document.documentElement.scrollTop) || 
         document.body.scrollTop;
        let scrollHeight = (document.documentElement && 
        document.documentElement.scrollHeight) || document.body.scrollHeight;
        let clientHeight = document.documentElement.clientHeight || window.innerHeight;
        let scrolledToBottom = Math.ceil(scrollTop + clientHeight) >= scrollHeight;
        console.log(scrolledToBottom);
    }

答案 1 :(得分:0)

发生这种情况是因为在这种情况下,<div class="panel-body"> <table> <thead> <tr> <th class="col-md-2">User</th> <th class="col-md-2"> Gruppe</th> </tr> </thead> <tbody> {!! Form::open(array('route'=>'store.exclusion')) !!} @foreach($members as $member) <tr> <td class="col-md-2" name="member" value="{{$member->member}}">{{$member->username}}</td> <td class="col-md-2" name="idgroup" value="{{$member->idgroup}}">{{$member->groupname}}</td> <td class="col-md-2">{{Form::submit('Ausschließen',['class' => 'btn btn-primary'])}}</td> </tr> @endforeach {!! Form::close() !!} </tbody> </table> </div> (即Document,而不是DOM元素。 DOM元素可以通过e.target === document到达。

这应该有效:

document.documentElement

请注意, handleScroll = (e) => { const el = e.target.documentElement; const bottom = el.scrollHeight - el.scrollTop === el.clientHeight; if (bottom) { console.log('we are in the bottom'); } } componentDidMount() { window.addEventListener('scroll',this.handleScroll); } 对箭头功能不起作用,因此不需要。它是带.bind(this)的箭头或原型方法。

答案 2 :(得分:0)

  componentDidMount = () => {
    window.addEventListener('scroll', this.handleScroll, true);
  };

  handleScroll = () => {
    const end =
      document.documentElement.scrollHeight -
        document.documentElement.scrollTop ===
      document.documentElement.clientHeight;

    if (end) {
      console.log('e,', end);
    }
  };