context/projects-context.js

    • 对外暴露的是 和useProjectsValue
    • 包裹要用这个context里值的组件
    • 在需要用context的组件里,通过 const { setSelectedProject } = useSelectedProjectValue ```javascript import React, { createContext, useContext } from ‘react’; import { useProjects } from ‘../hooks’;

    export const ProjectsContext = createContext(); export const ProjectsProvider = ({ children }) => { const { projects, setProjects } = useProjects();

    return ( {children} ); };

    export const useProjectsValue = () => useContext(ProjectsContext);

    1. **context/index.js**
    2. ```javascript
    3. import {
    4. ProjectsContext,
    5. ProjectsProvider,
    6. useProjectsValue,
    7. } from './projects-context';
    8. export {
    9. ProjectsContext,
    10. ProjectsProvider,
    11. useProjectsValue,
    12. };

    App.js

    1. import React from 'react';
    2. import { Header } from './components/layout/Header';
    3. import { Content } from './components/layout/Content';
    4. import { ProjectsProvider } from './context';
    5. export const App = () => {
    6. return (
    7. <ProjectsProvider>
    8. <div className="App">
    9. <Header />
    10. <Content />
    11. </div>
    12. </ProjectsProvider>
    13. );
    14. };

    Sidebar.js

    1. import React, { useState } from 'react';
    2. import {
    3. FaChevronDown,
    4. FaInbox,
    5. FaRegCalendarAlt,
    6. FaRegCalendar,
    7. } from 'react-icons/fa';
    8. import { useSelectedProjectValue } from '../../context';
    9. export const Sidebar = () => {
    10. const { setSelectedProject } = useSelectedProjectValue;
    11. const [active, setActive] = useState('inbox');
    12. const [showProjects, setShowProjects] = useState(true);
    13. return (
    14. <div className="sidebar" data-testid="sidebar">
    15. <ul className="sidebar__generic">
    16. <li data-testid="inbox" className="inbox">
    17. <span>
    18. <FaInbox />
    19. </span>
    20. <span>Inbox</span>
    21. </li>
    22. <li data-testid="today" className="today">
    23. <span>
    24. <FaRegCalendar />
    25. </span>
    26. <span>Today</span>
    27. </li>
    28. <li data-testid="next_7" className="next_7">
    29. <span>
    30. <FaRegCalendarAlt />
    31. </span>
    32. <span>Next 7 days</span>
    33. </li>
    34. </ul>
    35. <div className="sidebar__middle">
    36. <span>
    37. <FaChevronDown />
    38. </span>
    39. <h2>Projects</h2>
    40. </div>
    41. <ul className="sidebar__projects">Projects will be here!</ul>
    42. Add Project Component here!
    43. </div>
    44. );
    45. };