react Hooks usecontext 和useuseReducer 完成小案例

show.jsx

import React, { useContext } from "react";
import { Colorcontext } from "../App.js"
function A() {
  const count = useContext(Colorcontext)
  return (
  <div style={{color:count}}>
    我是文字,我现在变成了{count}
  </div>
  )
}
export default A

app.js

import './App.css';
import React from 'react'
import Show from "./components/show.jsx"
export const Colorcontext = React.createContext()
function App() {
  const [count, setcount] = React.useState({ a: 'red', b: 'yellow' })
  const [btn, dispatch] = React.useReducer((state, action) => {
    switch (action) {
      case "red":
        return "red"
      case "yellow":
        return "yellow"
    }
  }, "blue")
  return (
    <div id="App">
      <Colorcontext.Provider value={btn}>
        <Show></Show>
      </Colorcontext.Provider>
      <button onClick={() => { dispatch("red") }}>红色</button>
      <button onClick={() => { dispatch("yellow") }}>黄色</button>
    </div>
  );
}
export default App;

react Hooks usecontext 和useuseReducer 完成小案例
react Hooks usecontext 和useuseReducer 完成小案例
react Hooks usecontext 和useuseReducer 完成小案例

上一篇:NumPy测试题


下一篇:react hooks(useState、useEffect、useRef详解)