0
点赞
收藏
分享

微信扫一扫

记一次简单的获取虚拟机|伪终端shell权限

Gaaidou 03-08 09:00 阅读 3
import { useId } from 'react';

function PasswordField() {
  const passwordHintId = useId();
  return (
    <>
      <label>
        密码:
        <input
          type="password"
          aria-describedby={passwordHintId}
        />
      </label>
      <p id={passwordHintId}>
        密码应该包含至少 18 个字符
      </p>
    </>
  );
}

如果你需要为多个相关元素生成 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>
  );
}

如果你在单个页面上渲染多个独立的 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 />);

为什么要使用useId

React 支持开箱即用的同构,在同构应用中渲染列表时,如果我们没有一个唯一的 id,
很多人习惯使用 Math.random 或类似 uuid 这样的库来生成一个唯一 id。
但这些方法有一个共同的缺点:当程序运行时,由服务端生成的 uuid 或 Math.random
 会和客户端生成的不同。

React 的 useId hook 确保生成的 id 在组件内是唯一的。
举报

相关推荐

0 条评论