<div id="react-root"></div>
// Создаем контекст
const CompanyContext = React.createContext({});
// Компонент адреса компании
class CompanyAddressComponent extends React.Component {
// Компонент использует контекст
static contextType = CompanyContext;
render() {
// Извлекаем данные из контекста
const { context } = this;
const { address } = context;
return (
<>
{address.street}
<br />
{address.city}, {address.post}
<br />
{address.country}
</>
);
}
}
// Другой компонент отрисовывает название компании
class CompanyNameComponent extends React.Component {
// Оба компонента используют один контекст
static contextType = CompanyContext;
render() {
const { context } = this;
const { name } = context;
return <>{name}</>;
}
}
class App extends React.Component {
render() {
// Компоненты могут быть вложены на любой глубине
return (
<>
<CompanyNameComponent />
<br />
<CompanyAddressComponent />
</>
);
}
}
const company = {
name: "Google",
address: {
street: "100 Bay View Drive",
post: "CA 94043",
city: "Mountain View",
country: "USA"
}
};
const dom = (
<CompanyContext.Provider value={company}>
<App />
</CompanyContext.Provider>
);
const mountNode = document.getElementById("react-root");
const root = ReactDOM.createRoot(mountNode);
root.render(dom);
View Compiled
This Pen doesn't use any external CSS resources.