你不知道的React系列(二十五)useId

93 阅读1分钟

本文正在参加「金石计划」

const id = useId();
  • 生成唯一id,客户端和服务端都可以使用,需要在服务器和客户端上有相同的组件树
  • 不用当做key使用
  • 不能在css选择器和 querySelectorAll 中使用

为无障碍属性生成唯一 ID

import { useId } from 'react';

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

为多个相关元素生成 ID

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>
  );
}

为所有生成的 ID 指定共享前缀

提供前缀避免在多个root程序中冲突

createRoothydrateRoot 调用中使用 identifierPrefix

import { createRoot } from 'react-dom/client';
import App from './App.js';
import './styles.css';

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 />);