简体   繁体   English

javascript map 方法动态渲染时输入失去焦点

[英]Input loses focus when javascript map method is used to render it dynamically

const HeaderField = ({
  handleHeaderChange,
  removeHeader,
  index,
  header,
}: any) => (
  <HeaderContainer>
    <TextField
      label="Key"
      value={header.key}
      onChange={e => handleHeaderChange(e.target.value, 'key', index)}
    />
    <TextField
      label="Value"
      value={header.value}
      onChange={e => handleHeaderChange(e.target.value, 'value', index)}
    />
);

const CustomHeadersField = ({ handleChange, fieldKey, categoryKey }: any) => {
  const [headers, setHeaders] = React.useState<headersType[] | null>(null);

  const addHeader = () => {
    const newHeaders = headers ? [...headers] : [];
    newHeaders.push({ key: '', value: '' });
    setHeaders(newHeaders);
  };

  const handleHeaderChange = (
    value: string,
    type: 'key' | 'value',
    index: number,
  ) => {
    const newHeaders: any = headers ? [...headers] : [];
    if (type === 'key') {
      newHeaders[index].key = value;
    } else {
      newHeaders[index].value = value;
    }
    setHeaders(newHeaders);
    handleChange(newHeaders, fieldKey, categoryKey);
  };

  return (
    <CustomHeadersContainer>
      {headers?.map((header, index) => (
        <HeaderField
          key={Math.random()}
          handleHeaderChange={handleHeaderChange}
          removeHeader={removeHeader}
          index={index}
          header={header}
        />
      ))}
      <Button
        onClick={addHeader}
        variant="contained"
        sx={{ width: 'fit-content' }}
      >
        Add Header
      </Button>
    </CustomHeadersContainer>
  );
};

Add Header button adds a new key-value pair to the headers state, adding two new fields in the form.添加 Header按钮向标题 state 添加一个新的键值对,在表单中添加两个新字段。

Now header.map destroys the old components and renders new one for every key press causing it to lose focus.现在header.map会破坏旧组件并为每次按键呈现新组件,从而导致它失去焦点。

I tried moving HeaderField component out of CustomHeadersField .我尝试将HeaderField组件移出CustomHeadersField It didn't work.它没有用。

Thank you for the help!感谢您的帮助!

According to react documentation :根据反应文档

Keys should be stable, predictable, and unique.密钥应该是稳定的、可预测的和唯一的。 Unstable keys (like those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.不稳定的键(如 Math.random() 生成的键)会导致不必要地重新创建许多组件实例和 DOM 节点,这会导致性能下降并在子组件中丢失 state。

Passing Math.random() as a key is the issue.将 Math.random() 作为键传递是问题所在。 You can use index as a key if you are not reordering the list.如果您不对列表重新排序,则可以使用索引作为键。 Refer this answer参考这个答案

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

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