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 (
export const useProjectsValue = () => useContext(ProjectsContext);
**context/index.js**
```javascript
import {
ProjectsContext,
ProjectsProvider,
useProjectsValue,
} from './projects-context';
export {
ProjectsContext,
ProjectsProvider,
useProjectsValue,
};
App.js
import React from 'react';
import { Header } from './components/layout/Header';
import { Content } from './components/layout/Content';
import { ProjectsProvider } from './context';
export const App = () => {
return (
<ProjectsProvider>
<div className="App">
<Header />
<Content />
</div>
</ProjectsProvider>
);
};
Sidebar.js
import React, { useState } from 'react';
import {
FaChevronDown,
FaInbox,
FaRegCalendarAlt,
FaRegCalendar,
} from 'react-icons/fa';
import { useSelectedProjectValue } from '../../context';
export const Sidebar = () => {
const { setSelectedProject } = useSelectedProjectValue;
const [active, setActive] = useState('inbox');
const [showProjects, setShowProjects] = useState(true);
return (
<div className="sidebar" data-testid="sidebar">
<ul className="sidebar__generic">
<li data-testid="inbox" className="inbox">
<span>
<FaInbox />
</span>
<span>Inbox</span>
</li>
<li data-testid="today" className="today">
<span>
<FaRegCalendar />
</span>
<span>Today</span>
</li>
<li data-testid="next_7" className="next_7">
<span>
<FaRegCalendarAlt />
</span>
<span>Next 7 days</span>
</li>
</ul>
<div className="sidebar__middle">
<span>
<FaChevronDown />
</span>
<h2>Projects</h2>
</div>
<ul className="sidebar__projects">Projects will be here!</ul>
Add Project Component here!
</div>
);
};