react_hooks系列08_useId

179 阅读1分钟

useId是一个钩子,用于生成唯一的ID,在服务器和客户端之间是稳定的,同时避免hydration 不匹配。类似于Symbol , 也类似于uuid。

注意:

useId不是用来生成列表中的键的。Keys 应该从你的数据中生成。

对于一个基本的例子,直接将id传递给需要它的元素。

对于同一组件中的多个ID,使用相同的ID附加一个后缀。

如下例子,保证了元素id的唯一性。


import React, { useId, useState } from 'react'
 
function UseIdDemo() {
    
  const userId = useId()
  const passwordId = useId()
  const id = useId()
  const [list, setList] = useState(['a', 'b', 'c'])
  return (
    <div>
       <div>
        <label htmlFor='username'>用户名</label>
        <input id="username" type="text" placeholder='用户名' />
      </div> 
        <div>
        <label htmlFor={ userId }>用户名</label>
        <input id={userId} type="text" placeholder='用户名' />
      </div>
      <div>
        <label htmlFor={passwordId}>密码</label>
        <input id={passwordId} type="text" placeholder='密码' />
      </div> 
      <div>
        <label htmlFor={ id + '-user' }>用户名</label>
        <input id={ id + '-user' } type="text" placeholder='用户名' />
      </div>
      <div>
        <label htmlFor={ id + '-password' }>密码</label>
        <input id={ id + '-password' } type="text" placeholder='密码' />
      </div>
      <ul>
        {
          list.map(item => {
            // React Hook "useId" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function 
            // const id = useId()
            return (
              <li key={item}>{item}</li>
            )
          })
        }
      </ul>
    </div>
  )
}
 
export default UseIdDemo