简体   繁体   English

重新呈现整个播放列表的文本框上的onBlur函数阻止了切换至下一个文本框的功能

[英]onBlur function on a textbox that rerenders the whole playlist is preventing the ability to tab over to the next textbox

function handleBlur(event) {
  if (event.target.value !== props.value) {
    // a hook function that ends up rerendering the whole playlist
  }
}

i'm experimenting with React hooks and i have a playlist that holds a bunch of components that have input textboxes. 我正在试验React钩子,并且我有一个播放列表,其中包含一堆具有输入文本框的组件。 modifying an item in the list unfortunately seems to render the whole playlist component despite memoizing so I'm trying to move the save playlist function to onBlur instead of onChange. 不幸的是,尽管进行了修改,但修改列表中的一项似乎仍然呈现了整个播放列表组件,因此,我试图将保存播放列表功能移至onBlur而不是onChange。 but when I'm on a textbox and I tab over, once the re-render happens I lose the tab focus of the textbox I'm on. 但是当我在文本框上并按Tab键浏览时,一旦发生重新渲染,我将失去所在文本框的Tab键焦点。 Is there any way I can prevent this? 有什么办法可以防止这种情况? Any tips on how to prevent rerendering the whole playlist when i want to modify just an object in a list would be nice as well 当我只想修改列表中的一个对象时,如何防止重新呈现整个播放列表的任何提示也将很不错

playerList.map((player, index) => (
  <DraftPlayer
     arrayPosition={index}
     key={index + (Math.random()).toString()}
     modifyPlayer={modifyPlayer}  //hook function
     player={player}
   />
 ))

const [playerList, setPlayerList] = React.useState(
    initializePlayerListArray([ { firstName: "", lastName: "" },{ firstName: "", lastName: "" },{ firstName: "", lastName: "" },{ firstName: "", lastName: "" },{ firstName: "", lastName: "" },etc ])
  );

The issue you are experiencing is because you are setting a random key on every render cycle. 您遇到的问题是因为您要在每个渲染周期上设置一个随机密钥。 React uses the key for rendering performance, however when that key is randomized its telling react a new item is being rendered, or that it should be. React使用该键来提高渲染性能,但是当该键被随机分配时,它会告诉React正在渲染或应该渲染的新项目。 In turn the input is essentially unmounted then remounted in the DOM. 依次将输入卸载,然后在DOM中重新安装。 This is why you end up losing focus. 这就是为什么您最终失去焦点的原因。 Instead you should try to keep the key as constant as possible (relevant to the item that is being rendered). 相反,您应该尝试使密钥尽可能保持恒定(与要渲染的项目有关)。

I don't know the player model you are working with, but so were on the same page I'm going to write a typescript interface for the Player :) 我不知道您正在使用的播放器型号,但是在同一页面上,我将为播放器编写一个打字稿界面:)

interface Player {
  id: number
  firstname: string
  lastname: string
  /* ... etc */
}

Then I would create your items this way 然后我会用这种方式创建您的物品

playerList.map((player, index) => (
  <DraftPlayer
     arrayPosition={index}
     key={player.id}
     modifyPlayer={modifyPlayer}  //hook function
     player={player}
   />
))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM