父组件
import React, { useReducer } from 'react';
import DeepTree from './DeepTree';
const myContext = React.createContext(null);
export default function Parent() {
const Reducer = (state, action) => {
switch (action.type) {
case 'updateText':
return {
...state,
text: action.text
}
default:
return {
...state
}
}
};
const [state, dispatch] = useReducer(Reducer, {
text: 'xxx'
});
return (
<myContext.Provider value={dispatch}>
<div>
{state.text}
<DeepTree myContext={myContext} />
</div>
</myContext.Provider>
);
}
子组件
import React, { useContext } from "react";
export default function DeepTree(props) {
const dispatch = useContext(props.myContext);
const handleClick = () => {
dispatch({ type: 'updateText', text: 'hello' });
};
return (
<button onClick={handleClick}>updateText</button>
);
}