在React中实现滑动到指定初始块的功能可以通过ref和scrollIntoView方法来实现。

首先,你需要在父组件的state中添加一个属性来跟踪当前显示的块的索引。例如:

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibleBlockIndex: 0, // 当前可见块的索引
    };
  }
  
  render() {
    // 渲染子组件
  }
}

在子组件中,你可以使用ref来获取块的DOM元素的引用,并在组件加载完成后将其存储在父组件的state中。例如:

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.blockRef = React.createRef(); // 创建ref
  }
  
  componentDidMount() {
    // 在组件加载完成后,将块的引用存储在父组件的state中
    this.props.onBlockRef(this.blockRef.current);
  }
  
  render() {
    return (
      <div ref={this.blockRef}>块内容</div>
    );
  }
}

在父组件中,你可以创建一个方法来处理子组件加载完成后的回调,并在该方法中将块的引用存储在state中。例如:

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibleBlockIndex: 0,
      blockRefs: [], // 存储所有块的引用
    };
  }
  
  handleBlockRef = (ref) => {
    this.setState(prevState => ({
      blockRefs: [...prevState.blockRefs, ref], // 存储块的引用
    }));
  }
  
  render() {
    const { blockRefs, visibleBlockIndex } = this.state;
    
    // 渲染子组件并将处理块引用的方法传递给子组件
    return (
      <div>
        {blockRefs.map((ref, index) => (
          <ChildComponent key={index} onBlockRef={this.handleBlockRef} />
        ))}
      </div>
    );
  }
}

最后,在父组件中的componentDidMount方法中,你可以使用scrollIntoView方法将初始块滑动到可见区域。例如:

class ParentComponent extends React.Component {
  // ...
  
  componentDidMount() {
    const { blockRefs, visibleBlockIndex } = this.state;
    
    if (blockRefs[visibleBlockIndex]) {
      blockRefs[visibleBlockIndex].scrollIntoView({ behavior: 'smooth' }); // 滑动到初始块
    }
  }
  
  // ...
}

这样,当所有块加载完成后,界面会自动滑动到初始的第7个块

reactjs 横向分布了 10 个 block 只显示了 3 个 block如何在界面加载了所有 block 之后自动滑向那个初始的 block 处例如第 7 个

原文地址: https://www.cveoy.top/t/topic/hV6U 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录