2017-04-20 227 views
2

我目前有一個Feed組件。它接受一個data prop,這是一個項目數組,並且支持一個children prop,該prop用於將數據映射到DOM元素。保存ref作爲子功能創建的子項

現在,我正在嘗試創建功能以滾動到由children函數映射的此data屬性中的任何元素。但是,這意味着我需要存儲對它的引用。我不確定適當的語法/ api。這裏是我的基本代碼:

class ScrollableFeed extends Component { 
    static propTypes = { 
    data: PropTypes.array, 
    children: PropTypes.func, 
    }; 

    container = null; 

    render() { 
    const { data, children } = this.props; 
    return (
     <div 
     className={styles.feed} 
     onScroll={this.onScroll} 
     ref={e => { this.container = e; }} 
     > 
     {data.map(children)} 
     </div> 
    ); 
    } 
} 

爲了滾動到一個組成部分,我將需要已經由children函數映射出的DOM元素的引用。

這怎麼能做到反應?

+1

你可以分享'Feed'組件的代碼嗎? –

+0

哎呀抱歉,它是'ScrollableFeed'的代碼,只是類型不匹配 – corvid

+0

好吧,我的意思是代表'ScrollableFeed'的父代碼。 –

回答

0

想我找到了解決方案。 DOM元素有一個名爲childNodes的屬性。因此,我可以引用我的容器並獲取將由children映射出的子節點。然後我可以通過索引獲取節點。

getNodeAtIndex(index) { 
    const { childNodes = [] } = this.container; 
    const nodeIndex = Math.min(Math.max(index, 0), childNodes.length - 1); 
    return childNodes[nodeIndex]; 
}