My App

useId Hook

useId Hook

这是视频中的游乐场:

import React from 'react';

import LoginForm from './LoginForm';

function App() {
  return (
    <>
      <header>
        <LoginForm />
      </header>
      <main>
        <h1>Some Website</h1>
        <p>
          Lorem Ipsum is simply dummy text of the printing and
          typesetting industry. Lorem Ipsum has been the
          industry's standard dummy text ever since the 1500s,
          when an unknown printer took a galley of type and
          scrambled it to make a type specimen book. It has
          survived not only five centuries, but also the leap into
          electronic typesetting, remaining essentially unchanged.
        </p>
        <p>
          It was popularised in the 1960s with the release of
          Letraset sheets containing Lorem Ipsum passages, and
          more recently with desktop publishing software like
          Aldus PageMaker including versions of Lorem Ipsum.
        </p>
      </main>
      <footer>
        <LoginForm />
      </footer>
    </>
  );
}

export default App;

另一个好处

useId 钩子还有一个特别之处:它在服务器和客户端渲染中产生相同的值。这是一个非常特殊的属性,如果没有 React 提供的特殊解决方案,将很难重现。

在本课程的后面部分,我们将进一步了解服务器端渲染以及它带来的复杂性。

练习 — 切换组件

在这个沙盒中,您会发现一个几乎完全实现的 Toggle 组件。

通过为按钮添加一个唯一的 ID,并将其连接到标签来完成它。您应该能够通过点击“Dark Mode”文本来触发切换。

import React from 'react';

import Toggle from './Toggle';

function App() {
  const [isDarkMode, setIsDarkMode] = React.useState(false);

  return (
    <div
      className="wrapper"
      style={{
        // NOTE: This is a just-for-fun mini demo, not a
        // full-featured Dark Mode implementation!
        '--color-bg': isDarkMode ? 'black' : 'white',
        '--color-text': isDarkMode ? 'white' : 'black',
      }}
    >
      <Toggle
        label="Dark Mode"
        checked={isDarkMode}
        handleToggle={setIsDarkMode}
      />
    </div>
  );
}

export default App;

解决方案代码

On this page