React v18 introduces the new createRoot function which allows you to create a root outside of the main React tree. This can be useful for creating a tooltip component that is rendered outside of the main component hierarchy.

Here's an example of how you can create a simple tooltip component using React v18:

import { createRoot } from 'react-dom';
import { useState } from 'react';

function Tooltip({ content, children }) {
  const [isVisible, setIsVisible] = useState(false);

  const showTooltip = () => {
    setIsVisible(true);
  };

  const hideTooltip = () => {
    setIsVisible(false);
  };

  return (
    <div>
      <div onMouseEnter={showTooltip} onMouseLeave={hideTooltip}>
        {children}
      </div>
      {isVisible && <div className="tooltip">{content}</div>}
    </div>
  );
}

// Usage
const root = createRoot(document.getElementById('tooltip-root'));

function App() {
  return (
    <div>
      <h1>React v18 Tooltip Example</h1>
      <Tooltip content="This is a tooltip">
        <button>Hover Me</button>
      </Tooltip>
    </div>
  );
}

root.render(<App />);

In this example, we create a Tooltip component that accepts content and children props. The content prop represents the tooltip text, and the children prop represents the element that triggers the tooltip when hovered over.

We use the useState hook to manage the visibility state of the tooltip. When the element is hovered over, the showTooltip function sets the isVisible state to true, and the hideTooltip function sets it to false.

The tooltip is rendered conditionally based on the isVisible state. When isVisible is true, the tooltip is shown.

To render the App component and the tooltip outside of the main React tree, we use the createRoot function provided by React v18. We create a separate root element with the id tooltip-root and render the App component inside that root.

Make sure to have an HTML element with the id tooltip-root in your HTML file where the tooltip will be rendered.

You can customize the tooltip's appearance by adding CSS styles to the tooltip class

reactjs v18 自己做一个简单的tooltip

原文地址: http://www.cveoy.top/t/topic/iWa1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录