- Class 中自定義方法
- functional 在Hook中 使用useReducer
import React, { Component } from 'react' const UserContext = React.createContext() class UserProvider extends Component { // Context state state = { user: {}, } // Method to update state setUser = (user) => { this.setState((prevState) => ({ user })) } render() { const { children } = this.props const { user } = this.state const { setUser } = this return ( <UserContext.Provider value={{ user, setUser, }} > {children} </UserContext.Provider> ) } } export default UserContext export { UserProvider }
import React, { useReducer } from "react"; import Content from "./content"; import { CatStateContext } from "./context"; const initialState = { character: [ { id: "01", name: "湯姆貓", feature: "很蠢" }, startCatchMouse: false }; const reducer = (state, action) => { switch (action.type) { case "ADD_CONTACT": return { character: [...state.character, action.payload] //payload就是傳回來的資料 }; case "START": return { startCatchMouse: true }; default: throw new Error(); } }; export const ProviderContext = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <CatStateContext.Provider value={[state, dispatch]}> <Content /> </CatStateContext.Provider> ); }; //content.js import React, { useContext } from "react"; import { CatStateContext } from "./context"; export default (props) => { const [state, dispatch] = useContext(CatStateContext); const addContact = (event) => { dispatch({ type: "ADD_CONTACT", payload: { id: event.target.childNodes[0].childNodes[1].value, name: event.target.childNodes[1].childNodes[1].value, feature: event.target.childNodes[2].childNodes[1].value } }); event.preventDefault(); }; const table = state.character.map((value) => { return ( <div key={value.id} style={{ border: "1px solid green" }}> <p>編號 {value.id}</p> <h3>名字 {value.name}!</h3> <h3>特徵 {value.feature}</h3> <button onClick={() => delContact(value.id)}>刪除</button> </div> ); }); return ( <div> <form onSubmit={(e) => addContact(e)}> <p> id: <input required type="text" /> </p> <p> name <input required type="text" /> </p> <p> feature <input required type="text" /> </p> <button>新增</button> </form> {table} </div> ); };
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記