Я нашел решение благодаря этой статье: https://dev.to/email2vimalraj/react-hooks-lift-up--pass-down-state-using-usecontext-and-usereducer-5ai0 Решение, как описано, заключается в создании редуктора для файла мастера, чтобы мастер имел доступ к своим данным, а также к детям:
Wizard.jsx
import React, {
useState,
useEffect,
useLayoutEffect,
useContext,
useReducer
} from "react";
import PropTypes from "prop-types";
import "./wizard.scss";
import {
WizardContext,
wizardReducer,
SET_CURRENT_STEP,
SET_MAX_STEPS,
BACK,
NEXT
} from "./WizardContext";
function StepContent(props) {
const { selected, children, ...other } = props;
return (
<li {...other} selected={selected}>
{children}
</li>
);
}
function Wizard(props) {
const { onClose, onChange, pageContentClassName } = props;
function onClick(index) {
dispatch({ type: SET_CURRENT_STEP, currentStep: index });
// setSelected(index);
}
//get the progressBar steps
const steps = React.Children.map(props.children, page => {
const { id, label, description } = page.props;
return <div id={id} label={label} description={description} />;
});
function getContentAt(index) {
return stepContentWithProps[index];
}
const stepsWithProps = React.Children.map(props.children, (step, index) => {
const newStep = React.cloneElement(step, {});
return newStep;
});
const stepContentWithProps = stepsWithProps.map((step, index) => {
const { children } = step.props;
return (
<StepContent key={index} className={pageContentClassName}>
{children}
</StepContent>
);
});
const initialState = {
maxSteps: React.Children.count(props.children),
currentStep: 0
};
const [wizardData, dispatch] = useReducer(wizardReducer, initialState);
return (
<div className="wizard">
<p>This text is in wizard: currentStep={wizardData.currentStep}</p>
<WizardContext.Provider value={{ wizardData, dispatch }}>
<div className="wizard__upper">
<ul currentIndex={wizardData.currentStep} onChange={onClick}>
{steps}
</ul>
</div>
<div className="wizard__separator" />
<div className="wizard__content">{stepsWithProps}</div>
<div>
<button onClick={() => dispatch({ type: BACK })}>Back</button>
<button onClick={() => dispatch({ type: NEXT })}>Next</button>
</div>
</WizardContext.Provider>
</div>
);
}
Wizard.propTypes = {
/**
* Specify the text to be read by screen-readers when visiting the <Tabs>
* component
*/
ariaLabel: PropTypes.string,
/**
* Pass in a collection of <Tab> children to be rendered depending on the
* currently selected tab
*/
children: PropTypes.node,
/**
* Provide a className that is applied to the <PageContent> components
*/
pageContentClassName: PropTypes.string
};
export default Wizard;
WizardContext.jsx
import React, { createContext } from "react";
export const WizardContext = React.createContext(null);
export const SET_MAX_STEPS = "SET_MAX_STEPS";
export const SET_CURRENT_STEP = "SET_CURRENT_STEP";
export const BACK = "BACK";
export const NEXT = "NEXT";
export const SHOW_BACK = "SHOW_BACK";
export const SHOW_NEXT = "SHOW_NEXT";
export function wizardReducer(state, action) {
switch (action.type) {
case SET_MAX_STEPS:
return {
...state,
maxSteps: action.maxSteps
};
case SET_CURRENT_STEP:
if (action.currentStep >= state.maxSteps) return state;
return {
...state,
currentStep: action.currentStep
};
case BACK:
if (state.currentStep === 0) return state;
return {
...state,
currentStep: state.currentStep - 1
};
case NEXT:
if (state.currentStep >= state.maxSteps - 1) return state;
return {
...state,
currentStep: state.currentStep + 1
};
default:
return state;
}
}
Index.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import Wizard from "./Wizard";
import Cmp2 from "./Cmp2";
function App() {
const [wizardVisible, setWizardVisible] = useState(false);
return (
<div className="App">
<h1>
Wizard: why cant I see currentStep in wizard
<br />
(WORKING NOW!!!)
</h1>
<Wizard>
<div label="ddd">This is step1</div>
<Cmp2 />
<div label="ddd">This is step3</div>
</Wizard>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Cmp2.jsx
import React, { useState, useContext, useEffect } from "react";
import { WizardContext, SET_CURRENT_STEP } from "./WizardContext";
function Cmp2(props) {
const { wizardData, dispatch } = useContext(WizardContext);
return (
<div>
<br />
<p>This is Step 2</p>
{`in step2 (inner child of wizard): cur=${wizardData.currentStep}`}
<br />
<button
onClick={() => dispatch({ type: SET_CURRENT_STEP, currentStep: 1 })}
>
Click me to change current step
</button>
<br />
<br />
</div>
);
}
export default Cmp2;
Теперь мне нужно найти, как сделать его доступным, я имею в виду, что он работает хорошо, но когда я пытаюсь создать пользовательский хук (который импортирует контекст), контекст теряет значение при попытке использовать пользовательский хук (которыйПонятно, так как он вызывается в мастере ПЕРЕД провайдером), как добавить сюда улучшенную функциональность?
вот рабочее решение (без хука):
https://codesandbox.io/embed/wizardwitcontext-working-3lxhd