step:
1.import {createContext} from 'react';
2.createContext()
3.Context.Provider
4 useContext( )
App.js
import './App.css';
import BookList from './BookList';
import { BookProvider } from './BookContext';
function App() {
return (
<BookProvider>
<div className="App">
<BookList />
</div>
</BookProvider>
);
}
export default App;
BookContext.js
import React ,{useState,createContext}from 'react';
import BookList from './BookList';
export const BookContext = createContext();
export const BookProvider = (props) => {
const [books,setBooks] = useState([
{
name:'伊莉莎白女王傳',
price:'NT$525',
id:12345
},
{
name:'THINK逆思維',
price:'NT$332',
id:12346
},
{
name:'原子習慣',
price:'NT$261',
id:12347
},
{
name:'刻意練習',
price:'NT$253',
id:12348
}
]);
return (
<BookContext.Provider value={[books,setBooks]}>
{props.children}
</BookContext.Provider>
)
}
export default BookContext
BookList.js
import React,{useState,useContext} from 'react';
import Book from './Book';
import {BookContext} from './BookContext';
const BookList = () => {
const [books,setBooks] = useContext(BookContext) ;
return (
<div className='container'>
<h1>好書推薦書單</h1>
{books.map(book =>(
<Book
name={book.name}
price={book.price}
key={book.id} />
))}
</div>
)
}
export default BookList
Book.js
import React from 'react'
const Book = ({name,price}) => {
return (
<div>
<h3>{name}</h3>
<p>{price}</p>
</div>
)
}
export default Book