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;