iT邦幫忙

2022 iThome 鐵人賽

DAY 7
0
Modern Web

React應用記錄誌系列 第 7

Day07 實作練習React Context API

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20220922/20139800nlgn6GS2sm.png

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

上一篇
Day06 React Context
下一篇
Day08 React Router V6
系列文
React應用記錄誌31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言