[英]Managing scroll state between sibling components in React/Redux
React 組件如何控制兄弟組件的滾動位置?
Parent
是父組件,它有子List
(它包含一個可滾動的 div)和帶有按鈕的Actions
,該按鈕應該控制List
可滾動 div 的滾動。
一些選項:
Parent
管理滾動。 不知何故Parent
需要對List
的可滾動 div 進行 DOM 引用,不確定List
如何傳遞引用。VirtualScroll
) 的東西在List
顯示虛擬內容。 不要實際滾動,只需將內容更新為在新滾動位置看到的內容。 這意味着我們不能為滾動設置動畫?選項#2 似乎最合理(動畫滾動對於這種情況很重要),但我對 React/Redux 中的最佳實踐不夠熟悉,無法做出良好的架構決策。
我會選擇選項 2。但是除了將它們作為子組件之外,父級不應該保留對 List 項的引用。 您可以將滾動位置保存在 redux 存儲中,讓父級控制它,然后將其作為道具傳遞給您的列表項。
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import List from './List';
class Parent extends Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
scrollPos: PropTypes.number.isRequired
};
updateScrollPos() {
const value = getValueFromSomewhere();
this.dispatch({ type: UPDATE_SCROLLPOS, value })
}
render() {
return <div>
<button onClick={::this.updateScrollPos}>Update scrollPos</button>
<List scrollPos={this.props.scrollPos} />
<List scrollPos={this.props.scrollPos} />
<List scrollPos={this.props.scrollPos} />
</div>
}
}
const select = (state) => ({
scrollPos: state.scrollPos
})
export default connect(select)(Parent);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.