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;
标签:count,React,const,useuseReducer,Hooks,return,yellow,react,import 来源: https://blog.csdn.net/weixin_50736511/article/details/121135051