在 React/Redux 中管理同级组件之间的滚动状态
Managing scroll state between sibling components in React/Redux
React 组件如何控制兄弟组件的滚动位置?
Parent
是父组件,它有子组件 List
(其中包含一个可滚动的 div)和 Actions
以及一个应该控制滚动的按钮List
可滚动 div.
部分选项:
- 维护对可滚动 div 的 DOM 元素的引用和 Redux 商店中的滚动位置。在状态更改时触发减速器中的滚动。
Parent
管理滚动条。不知何故 Parent
需要 DOM 对 List
中可滚动 div 的引用,不确定 List
如何传递引用。
- 使用 react virtualized (
VirtualScroll
) 之类的东西在 List
中显示虚拟内容。不要实际滚动,只需将内容更新为在新滚动位置看到的内容。这意味着我们无法为滚动设置动画?
选项 #2 似乎最合理(动画滚动在此上下文中很重要),但我对 React/Redux 中的最佳实践不够熟悉,无法做出好的架构决策。
我会选择选项 2。但是除了将列表项作为子组件外,父项不必保留对列表项的引用。您可以将滚动位置保存在 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);
React 组件如何控制兄弟组件的滚动位置?
Parent
是父组件,它有子组件 List
(其中包含一个可滚动的 div)和 Actions
以及一个应该控制滚动的按钮List
可滚动 div.
部分选项:
- 维护对可滚动 div 的 DOM 元素的引用和 Redux 商店中的滚动位置。在状态更改时触发减速器中的滚动。
Parent
管理滚动条。不知何故Parent
需要 DOM 对List
中可滚动 div 的引用,不确定List
如何传递引用。- 使用 react virtualized (
VirtualScroll
) 之类的东西在List
中显示虚拟内容。不要实际滚动,只需将内容更新为在新滚动位置看到的内容。这意味着我们无法为滚动设置动画?
选项 #2 似乎最合理(动画滚动在此上下文中很重要),但我对 React/Redux 中的最佳实践不够熟悉,无法做出好的架构决策。
我会选择选项 2。但是除了将列表项作为子组件外,父项不必保留对列表项的引用。您可以将滚动位置保存在 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);