在 React/Redux 中管理同级组件之间的滚动状态

Managing scroll state between sibling components in React/Redux

本文关键字:之间 组件 滚动 状态 React Redux 管理      更新时间:2023-09-26

React 组件如何控制同级组件的滚动位置?

Parent是父组件,它有子List(包含可滚动的div(和Actions带有一个按钮,该按钮应该控制List可滚动div 的滚动。

一些选项:

  1. 在 Redux 存储中维护对可滚动div 和滚动位置的 DOM 元素的引用。在状态更改时触发化简器中的滚动。
  2. Parent管理滚动。不知何故,Parent需要对 List 中的可滚动div 有一个 DOM 引用,不确定List如何传递引用。
  3. 使用类似 反应虚拟化 (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);