seo建站网络公司,济南asp网站制作公司,无锡设计网站公司,购买游戏软件做网站useId()
在组件的顶层调用 useId 生成唯一 ID#xff1a;
import { useId } from react; function PasswordField() {
const passwordHintId useId();
// ...参数
useId 不带任何参数。
返回值
useId 返回一个唯一的字符串 ID#xff0c;与此特定组件中的 useI…useId()
在组件的顶层调用 useId 生成唯一 ID
import { useId } from react; function PasswordField() {
const passwordHintId useId();
// ...参数
useId 不带任何参数。
返回值
useId 返回一个唯一的字符串 ID与此特定组件中的 useId 调用相关联。
注意事项
useId 是一个 Hook因此你只能 在组件的顶层 或自己的 Hook 中调用它。你不能在内部循环或条件判断中调用它。如果需要可以提取一个新组件并将 state 移到该组件中。useId 不应该被用来生成列表中的 key。key 应该由你的数据生成。
用法
为无障碍属性生成唯一 ID
在组件的顶层调用 useId 生成唯一 ID
import { useId } from react;function PasswordField() {const passwordHintId useId();// ...你可以将 生成的 ID 传递给不同的属性
input typepassword aria-describedby{passwordHintId} /p id{passwordHintId}
/让我们通过一个例子看看这个什么时候有用。
如 aria-describedby 这样的 HTML 无障碍属性 允许你指定两个标签之间的关系。例如你可以指定一个元素比如输入框由另一个元素比如段落描述。
在常规的 HTML 中你会这样写
label密码:inputtypepasswordaria-describedbypassword-hint//label
p idpassword-hint密码应该包含至少 18 个字符
/p然而在 React 中直接编写 ID 并不是一个好的习惯。一个组件可能会在页面上渲染多次但是 ID 必须是唯一的不要使用自己编写的 ID而是使用 useId 生成唯一的 ID。
import { useId } from react;function PasswordField() {const passwordHintId useId();return (label密码:inputtypepasswordaria-describedby{passwordHintId}//labelp id{passwordHintId}密码应该包含至少 18 个字符/p/);
}现在即使 PasswordField 多次出现在屏幕上生成的 ID 并不会冲突。
import { useId } from react;function PasswordField() {const passwordHintId useId();return (label密码:inputtypepasswordaria-describedby{passwordHintId}//labelp id{passwordHintId}密码应该包含至少 18 个字符/p/);
}export default function App() {return (h2输入密码/h2PasswordField /h2验证密码/h2PasswordField //);
} 为多个相关元素生成 ID
如果你需要为多个相关元素生成 ID可以调用 useId 来为它们生成共同的前缀
import { useId } from react;export default function Form() {const id useId();return (formlabel htmlFor{id -firstName}名字/labelinput id{id -firstName} typetext /hr /label htmlFor{id -lastName}姓氏/labelinput id{id -lastName} typetext //form);
}
可以使你避免为每个需要唯一 ID 的元素调用 useId。 为所有生成的 ID 指定共享前缀
如果你在单个页面上渲染多个独立的 React 应用程序请在 createRoot 或 hydrateRoot 调用中将 identifierPrefix 作为选项传递。这确保了由两个不同应用程序生成的 ID 永远不会冲突因为使用 useId 生成的每个 ID 都将以你指定的不同前缀开头。
index.html
!DOCTYPE html
htmlheadtitleMy app/title/headbodydiv idroot1/divdiv idroot2/div/body
/html
App.js
import { useId } from react;function PasswordField() {const passwordHintId useId();console.log(生成的 ID, passwordHintId)return (label密码:inputtypepasswordaria-describedby{passwordHintId}//labelp id{passwordHintId}密码应该包含至少 18 个字符/p/);
}export default function App() {return (h2输入密码/h2PasswordField //);
}
index.js
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 /); useId – React 中文文档 (docschina.org)