如何将焦点移动到 React js 中的项目?

我已经在我的演示应用程序中实现了一个无限滚动的列表。单击任何行它将转到detail screen。它工作正常。

**我面临着关注最后选定行的问题**换句话说

  1. 运行应用程序。加载第一个20项目。滚动到底部以加载更多 20 个项目。

  2. 然后单击任何项目让说33rd row 。它将显示33在详细信息页面中。

  3. 现在单击back它显示焦点的按钮0或第一行。我想将焦点移动到33行。或者将滚动位置移动到33位置。

我使用useContextapi 来存储items(所有行/数据直到最后一次滚动)和selected item(选定的索引)。

这是我的代码 https://codesandbox.io/s/dank-cdn-2osdg?file=/src/useInfinitescroll.js

import React from "react";

import { withRouter } from "react-router-dom";

import { useListState } from "./context";

function Detail({ location, history }) {

  const state = useListState();

  console.log(state);

  return (

    <div className="App">

      <button

        onClick={() => {

          history.replace({

            pathname: "/"

          });

        }}

      >

        back

      </button>

      <h2>{location.state.key}</h2>

      <h1>detaiils</h1>

    </div>

  );

}


export default withRouter(Detail);



 any update?


慕斯王
浏览 128回答 2
2回答

偶然的你

在重定向到详细页面并将其存储在状态之前使用它。let&nbsp;position&nbsp;=&nbsp;document.documentElement.scrollTop这将给出您在页面上的当前位置。一旦你回到列表视图使用window.scrollTo(0,&nbsp;position)回到你最初所在的地方。

RISEBY

您的元素位置可能只有一个真实来源。作为示例,我将位置状态放在 Router 组件上,因为这似乎是 App 组件和 Details 的父级。const Router = () => {&nbsp; const [previousClickedItemPos, setPreviousClickedItemPos] = useState(0);&nbsp;&nbsp;&nbsp; /* import useLocation so that useEffect can be invoked on-route-change */&nbsp; const location = useLocation();&nbsp; /* basically pass this to the list items so you can update position on-click */&nbsp; function handleClickList(element) {&nbsp; &nbsp; setPreviousClickedItemPos(element);&nbsp; }&nbsp; useEffect(() => {&nbsp; &nbsp; /* scroll to the element previously selected */&nbsp; &nbsp; window.scrollTo(0, previousClickedItemPos);&nbsp; }, [previousClickedItemPos, location]);&nbsp; ...在您的 InfiniteList 组件上:<ListItem&nbsp; &nbsp; onClick={e => {&nbsp; &nbsp; &nbsp; &nbsp; dispatch({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "set",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; payload: items&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; handleClickList(e.target.offsetTop); /* update position state */&nbsp; &nbsp; &nbsp; &nbsp; goDetailScreen(item);&nbsp; &nbsp; }}&nbsp; &nbsp; key={item.key}>&nbsp; &nbsp; {item.value}</ListItem>代码沙盒: https ://codesandbox.io/s/modern-breeze-nwtln ?file=/src/router.js
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript