• react hook: useId


    React 中直接编写 ID 并不是一个好的习惯。一个组件可能会在页面上渲染多次,但是 ID 必须是唯一的!不要使用自己编写的 ID,而是使用 useId 生成唯一的 ID。
    现在,即使 PasswordField 多次出现在屏幕上,生成的 ID 并不会冲突。

    import { useId } from 'react';
    
    function PasswordField() {
      const passwordHintId = useId();
      return (
        <>
          <label>
            密码:
            <input
              type="password"
              aria-describedby={passwordHintId}
            />
          </label>
          <p id={passwordHintId}>
            密码应该包含至少 18 个字符
          </p>
        </>
      );
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    如果你需要为多个相关元素生成 ID,可以调用 useId 来为它们生成共同的前缀:
    可以使你避免为每个需要唯一 ID 的元素调用 useId。

    import { useId } from 'react';
    
    export default function Form() {
      const id = useId();
      return (
        <form>
          <label htmlFor={id + '-firstName'}>名字:</label>
          <input id={id + '-firstName'} type="text" />
          <hr />
          <label htmlFor={id + '-lastName'}>姓氏:</label>
          <input id={id + '-lastName'} type="text" />
        </form>
      );
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    如果你在单个页面上渲染多个独立的 React 应用程序,请在 createRoot 或 hydrateRoot 调用中将 identifierPrefix 作为选项传递。这确保了由两个不同应用程序生成的 ID 永远不会冲突,因为使用 useId 生成的每个 ID 都将以你指定的不同前缀开头。

    const root1 = createRoot(document.getElementById('root1'), {
      identifierPrefix: 'my-first-app-'
    });
    root1.render(<App />);
    
    const root2 = createRoot(document.getElementById('root2'), {
      identifierPrefix: 'my-second-app-'
    });
    root2.render(<App />);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    为什么要使用useId

    React 支持开箱即用的同构,在同构应用中渲染列表时,如果我们没有一个唯一的 id,
    很多人习惯使用 Math.random 或类似 uuid 这样的库来生成一个唯一 id。
    但这些方法有一个共同的缺点:当程序运行时,由服务端生成的 uuid 或 Math.random
     会和客户端生成的不同。
    
    React 的 useId hook 确保生成的 id 在组件内是唯一的。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 相关阅读:
    解决pycharm无法使用install package
    一个对安卓日志输出功能的优化
    Visual Studio 2022开发Arduino详述
    java与es8实战之五:SpringBoot应用中操作es8(带安全检查:https、账号密码、API Key)
    MySQL 主从 AUTO_INCREMENT 不一致问题分析
    MySQL查询性能优化解决方案
    java Process 执行批命令 cmd
    uniapp 小程序优惠劵样式
    Modbus TCP转CanOpen网关携手FANUC机器人助力新能源汽车
    Python编程技巧 – 使用列表(list)
  • 原文地址:https://blog.csdn.net/qq_36413371/article/details/136526482