2016-07-19 63 views
2

如何在組件中添加onScroll偵聽器來捕獲父元素的滾動?React - 父元素的onScroll偵聽器?

class ChildDiv extends React.Component { 
    constructor() { 
    super(); 
    } 
    handleScrollOfParent() { 
    // do stuff when parent <main> scrolls; 
    } 
    render() { 
    return (
     <div id="child" onScroll={this.handleScrollOfParent.bind(this)}> 
     // content with overflow: hidden and scroll handled by parent MAIN. 
     </div> 
    ) 
    } 
} 
export default ChildDiv; 

渲染父主,這樣<main><ChildDiv /></main>,我想抓住主要的滾動。

+0

你找到你的解決方案還沒有,我只是下面貼 – thinhvo0108

回答

1

您可以在每次發生事件時在父組件中定義一個狀態變量來存儲當前的scrollTop值(假定爲垂直滾動)並更新,然後將該變量傳遞給ChildDiv,該變量可以檢測到該變量具有在componentWillReceiveProps改變:

if(this.props.yourVariable != nextProps.yourVariable){ 
// scroll event was fired => scroll position changed 
} 
+0

回答這是「我怎樣才能在COMPONE添加onScroll聽衆真正的答案nt來捕獲父元素的滾動?「 – Mika

0

根據反應的性質,這是通過道具家長到孩子,所以當你想要的子元素,以更新其父母,你需要創建父函數,並傳遞到Child as props

請同時參閱我的回答類似的問題(如何觸發父組件從子/孫/或曾孫做什麼):

Re-initializing class on redirect

在你的情況,我們可以做些什麼像這樣:

1 /創建觸發家長本身做一些事情上家長的函數:

import React from 'react'; 

class Parent extends React.Component { 

    constructor(props) { 
    super(props); 
    // ... 
    } 

    doSomeThingOnParent =() => { 
    // do whatever you want with this Parent component, setState, forceUpdate etc. 
    } 

    render(){ 
    // ... 
    <Child doSomeThingOnParent={this.doSomeThingOnParent} /> 
    // ... 
    } 
} 

2 /在輔元件,使用onScroll觸發上述功能:

class Child extends React.Component { 
    ... 
    render() { 
    return (
     <div id="child" onScroll={this.props.doSomeThingOnParent}> 
     // your content 
     </div> 
    ) 
    } 
} 

但是,你不能用你提到的方式,這是使家長:

你應該像使用父的渲染上面的方法,並且還設置了CSS允許溢出你子組件

+0

OP明確表示,他們希望爲「主」而不是「小孩」捕捉滾動事件。在你的例子中,你展示瞭如何在main中獲得一個子滾動事件,這正好相反。 @ igorsvee的解決方案可以完成OP要求的內容。另一種解決方案是在父級中使用滾動處理程序,然後通過在''上使用'ref'來調用子組件中的方法。 – vinnymac

+1

@vinnymac感謝您的評論,似乎在這裏真的發生了誤會^^實際上,OP的第一句話是「我怎樣才能在組件中添加onScroll監聽器來捕獲父元素的滾動?」,該指示指示我以上面的例子。但是,OP的代碼示例以某種方式顯示了相反的方式^^所以實際上,如果真的需要相反的方式,那麼你是對的,使用componentWillReceiveProps可能會實現這一點。謝謝! – thinhvo0108

0

你既可以:

1)試圖抓住從子組件的父節點:

componentDidMount() { 
    ReactDOM.findDOMNode(this).parentNode.addEventListener(... 
} 

2)通過作爲道具父節點和附加渲染後監聽器:

在父:

render{ 
    return(
    <div className="parent" ref={(elem)=>{this.node=elem}}> 
     <Child parentNode={this.node}/> 
    </div> 
) 
} 

和在兒童(parentNode仍然未定義在構造函數中,檢查下一個道具):

componentWillReceiveProps(newProps){ 
    newProps.parentNode.addEventListener(... 
} 
相關問題