重新呈现整个播放列表的文本框上的 onBlur 功能阻止了切换到下一个文本框的能力 [英] onBlur function on a textbox that rerenders the whole playlist is preventing the ability to tab over to the next textbox

查看:41
本文介绍了重新呈现整个播放列表的文本框上的 onBlur 功能阻止了切换到下一个文本框的能力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在试验 React 钩子,我有一个播放列表,其中包含一堆具有输入文本框的组件.不幸的是,尽管进行了记忆,但修改列表中的项目似乎会呈现整个播放列表组件,因此我试图将保存播放列表功能移动到 onBlur 而不是 onChange.但是当我在一个文本框上并且我选择了标签时,一旦重新渲染发生,我就会失去我所在文本框的标签焦点.有什么办法可以防止这种情况吗?当我只想修改列表中的一个对象时,有关如何防止重新呈现整个播放列表的任何提示也很好

i'm experimenting with React hooks and i have a playlist that holds a bunch of components that have input textboxes. 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. 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. 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 ])
  );

推荐答案

您遇到的问题是因为您在每个渲染周期都设置了一个随机键.React 使用键来渲染性能,但是当该键被随机化时,它会告诉 React 正在渲染一个新项目,或者它应该被渲染.反过来,输入基本上被卸载,然后在 DOM 中重新安装.这就是你最终失去注意力的原因.相反,您应该尽量保持密钥不变(与正在呈现的项目相关).

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. In turn the input is essentially unmounted then remounted in the 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}
   />
))

这篇关于重新呈现整个播放列表的文本框上的 onBlur 功能阻止了切换到下一个文本框的能力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆