实现

    API使用

    1. import { useState, createContext, useContext } from "react";
    2. import ReactDOM from "react-dom";
    3. const UserContext = createContext();
    4. function Component1() {
    5. const [user, setUser] = useState("Jesse Hall");
    6. return (
    7. <UserContext.Provider value={user}>
    8. <h1>{`Hello ${user}!`}</h1>
    9. <Component2 user={user} />
    10. </UserContext.Provider>
    11. );
    12. }
    13. function Component2() {
    14. return (
    15. <>
    16. <h1>Component 2</h1>
    17. <Component3 />
    18. </>
    19. );
    20. }
    21. function Component3() {
    22. return (
    23. <>
    24. <h1>Component 3</h1>
    25. <Component4 />
    26. </>
    27. );
    28. }
    29. function Component4() {
    30. return (
    31. <>
    32. <h1>Component 4</h1>
    33. <Component5 />
    34. </>
    35. );
    36. }
    37. function Component5() {
    38. const user = useContext(UserContext);
    39. return (
    40. <>
    41. <h1>Component 5</h1>
    42. <h2>{`Hello ${user} again!`}</h2>
    43. </>
    44. );
    45. }
    46. ReactDOM.render(<Component1 />, document.getElementById("root"));