2017-04-24 78 views
1

我有一個父組件,它一開始沒有高度,但會隨着子組件的增加而增長。添加子元素後,我可以上下滾動,但是我注意到handleScroll函數沒有被觸發。React onScroll不從父組件開火

任何人都有類似的問題?

constructor() { 
    super(); 
    this.handleScroll = this.handleScroll.bind(this); 
} 
handleScroll(e) { 
    console.log(e); 
} 
render() { 
    return (
    <div className="parent" onScroll={this.handleScroll}> 
    { 
     this.props.children.map((child)=>{ 
     <div>{child.name}</div> 
     }) 
    } 
) 
} 
+0

什麼你的'div.parent'風格?它是否包含「overflow:scroll;」屬性並且在渲染時確實溢出了? –

回答

0

您可以通過這樣的滾動功能綁定到DIV:

import ReactDOM from 'react-dom'; 
// ... 

constructor() { 
    super(); 
    this.handleScroll = this.handleScroll.bind(this); 
} 
componentDidMount() { 
    const div = ReactDOM.findDOMNode(this.refs.someRef) 
    div.addEventListener('scroll', this.handleScroll); 
} 
componentWillUnmount() { 
    const div = ReactDOM.findDOMNode(this.refs.someRef) 
    div.removeEventListener('scroll', this.handleScroll); 
} 
handleScroll(e) { 
    console.log(e); 
} 
render() { 
    return (
    <div ref="someRef" className="parent"> 
    { 
     this.props.children.map((child)=>{ 
     <div>{child.name}</div> 
     }) 
    } 
    </div> 
) 
} 

..和也請同時設置CSS爲您的DIV爲:

.parent{ 
    overflow-y: auto; 
}