반응의 맥락은 무엇입니까
React에서 컨텍스트는 컴포넌트의 각 레이어에 대한 props를 수동으로 추가하지 않고 컴포넌트 트리 간에 데이터를 전송하는 방법입니다. 컨텍스트는 컴포넌트 트리를 통해 레이어별로 props를 명시적으로 전달할 필요 없이 컴포넌트 간에 지정된 값을 공유하는 방법을 제공합니다. .
이 튜토리얼의 운영 환경: Windows 10 시스템, 반응 버전 17.0.1, Dell G3 컴퓨터.
React에서 컨텍스트란 무엇인가요?
컨텍스트는 각 구성 요소 레이어에 소품을 수동으로 추가하지 않고도 구성 요소 트리 간에 데이터를 전송하는 방법을 제공합니다. 일반적인 React 애플리케이션에서 데이터는 props를 통해 위에서 아래로(상위에서 하위로) 전달되지만 이 접근 방식은 특정 유형의 속성(예: 로케일 기본 설정, UI 테마)에 대해 매우 번거롭습니다. 응용 프로그램. 컨텍스트는 컴포넌트 트리의 각 레벨을 통해 props를 명시적으로 전달하지 않고도 컴포넌트 간에 이러한 값을 공유할 수 있는 방법을 제공합니다.
Context 언제 사용하나요?
컨텍스트는 현재 인증된 사용자, 테마 또는 기본 언어와 같은 구성 요소 트리에 "전역"인 데이터를 공유하도록 설계되었습니다. 예를 들어, 아래 코드에서는 "테마" 속성을 통해 버튼 구성 요소의 스타일을 수동으로 조정합니다
class App extends React.Component { render() { return <Toolbar theme="dark" />; } } function Toolbar(props) { // Toolbar 组件接受一个额外的“theme”属性,然后传递给 ThemedButton 组件。 // 如果应用中每一个单独的按钮都需要知道 theme 的值,这会是件很麻烦的事, // 因为必须将这个值层层传递所有组件。 return ( <p> <ThemedButton theme={props.theme} /> </p> ); } class ThemedButton extends React.Component { render() { return <Button theme={this.props.theme} />; } } // 通过props传递:App -> Toolbar -> ThemedButton // 如果嵌套很深,那么需要逐层传递props,即使中间不需要该props,显得很繁琐
컨텍스트를 사용하여 중간 요소를 통해 소품이 전달되는 것을 피할 수 있습니다
// Context 可以让我们无须明确地传遍每一个组件,就能将值深入传递进组件树。 // 为当前的 theme 创建一个 context("light"为默认值)。 const ThemeContext = React.createContext('light'); class App extends React.Component { render() { // 使用一个 Provider 来将当前的 theme 传递给以下的组件树。 // 无论多深,任何组件都能读取这个值。 // 在这个例子中,我们将 “dark” 作为当前的值传递下去。 return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); } } // 中间的组件再也不必指明往下传递 theme 了。 function Toolbar() { return ( <p> <ThemedButton /> </p> ); } class ThemedButton extends React.Component { // 指定 contextType 读取当前的 theme context。 // React 会往上找到最近的 theme Provider,然后使用它的值。 // 在这个例子中,当前的 theme 值为 “dark”。 static contextType = ThemeContext; render() { return <Button theme={this.context} />; } } // 也可以使用 ThemedButto.contextType = ThemeContext;
API 소개
React.createContext
React.createContext
const MyContext = React.createContext(defaultValue);
创建一个 Context 对象。当 React 渲染一个订阅了这个 Context 对象的组件,这个组件会从组件树中离自身最近的那个匹配的 Provider
中读取到当前的 context 值。
只有当组件所处的树中没有匹配到 Provider 时,其 defaultValue
参数才会生效。这有助于在不使用 Provider 包装组件的情况下对组件进行测试。注意:将 undefined
传递给 Provider 的 value 时,消费组件的 defaultValue
不会生效。
Context.Provider
<MyContext.Provider value={/* 某个值 */}>
每个 Context 对象都会返回一个 Provider React 组件,它允许消费组件订阅 context 的变化。
Provider 接收一个 value
属性,传递给消费组件。一个 Provider 可以和多个消费组件有对应关系。多个 Provider 也可以嵌套使用,里层的会覆盖外层的数据。
当 Provider 的 value
值发生变化时,它内部的所有消费组件都会重新渲染。Provider 及其内部 consumer 组件都不受制于 shouldComponentUpdate
函数,因此当 consumer 组件在其祖先组件退出更新的情况下也能更新。
Class.contextType
挂载在 class 上的 contextType
属性会被重赋值为一个由 React.createContext() 创建的 Context 对象。这能让你使用 this.context
来消费最近 Context 上的那个值。你可以在任何生命周期中访问到它,包括 render 函数中
import MyContext from './MyContext'; class MyClass extends React.Component { componentDidMount() { let value = this.context; /* 在组件挂载完成后,使用 MyContext 组件的值来执行一些有副作用的操作 */ } componentDidUpdate() { let value = this.context; /* ... */ } componentWillUnmount() { let value = this.context; /* ... */ } render() { let value = this.context; /* 基于 MyContext 组件的值进行渲染 */ } // 或者如上边例子一样使用 static contextType = MyContext; } MyClass.contextType = MyContext;
Context.Consumer
import MyContext from './MyContext'; function ToolList() { return ( <MyContext.Consumer {value => /* 基于 context 值进行渲染*/} </MyContext.Consumer> ) }
这里,React 组件也可以订阅到 context 变更。这能让你在函数式组件中完成订阅 context。
这需要函数作为子元素(function as a child)这种做法。这个函数接收当前的 context 值,返回一个 React 节点。传递给函数的 value
值等同于往上组件树离这个 context 最近的 Provider 提供的 value
值。如果没有对应的 Provider,value
参数等同于传递给 createContext()
的 defaultValue
。
Context.displayName
context 对象接受一个名为 displayName
const MyContext = React.createContext(/* some value */); MyContext.displayName = 'MyDisplayName'; <MyContext.Provider> // "MyDisplayName.Provider" 在 DevTools 中 <MyContext.Consumer> // "MyDisplayName.Consumer" 在 DevTools 中
Context 객체를 생성합니다. React가 이 Context 객체를 구독하는 구성 요소를 렌더링할 때 구성 요소는 구성 요소 트리에서 자신과 가장 가까운 일치하는 Provider
에서 현재 컨텍스트 값을 읽습니다.
구성 요소가 있는 트리에 일치하는 공급자가 없는 경우에만 해당 defaultValue
매개 변수가 적용됩니다. 이는 구성 요소를 공급자로 래핑하지 않고 테스트하는 데 도움이 됩니다. 참고: 정의되지 않음
이 공급자 값에 전달되면 소비자 구성 요소의 defaultValue
가 적용되지 않습니다.
Context.Provider
export const themes = {
light: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
};
export const ThemeContext = React.createContext(themes.dark); // 该处为默认值
로그인 후 복사각 Context 개체는 구성 요소를 사용하여 컨텍스트 변경 사항을 구독할 수 있는 Provider React 구성 요소를 반환합니다.
Provider는 Context.Provider
export const themes = { light: { foreground: '#000000', background: '#eeeeee', }, dark: { foreground: '#ffffff', background: '#222222', }, }; export const ThemeContext = React.createContext(themes.dark); // 该处为默认值
value
속성을 받아 소비 구성 요소에 전달합니다. 공급자는 여러 소비자 구성 요소와 대응 관계를 가질 수 있습니다. 여러 공급자를 중첩하여 사용할 수도 있으며 내부 레이어가 외부 레이어의 데이터를 덮어씁니다.
공급자의 값
값이 변경되면 그 내부의 모든 소비 구성 요소가 다시 렌더링됩니다. Provider와 내부 소비자 구성 요소 모두 shouldComponentUpdate
함수의 적용을 받지 않으므로 상위 구성 요소가 업데이트를 종료하더라도 소비자 구성 요소를 업데이트할 수 있습니다. Class.contextType
Class.contextType
클래스에 마운트된 contextType
속성은 React.createContext() Context 객체에 의해 생성된 속성으로 다시 할당됩니다. 이를 통해 this.context
를 사용하여 가장 최근 컨텍스트의 값을 사용할 수 있습니다. 렌더링 함수
import { ThemeContext } from './theme-context'; class ThemedButton extends React.Component { render() { let props = this.props; // 获取到ThemeContext中的默认值 let theme = this.context; return ( <button {...props} style={{backgroundColor: theme.background}} /> ); } // static contextType = ThemeContext; } ThemedButton.contextType = ThemeContext; export default ThemedButton;
Context.Consumer
import { ThemeContext, themes } from './theme-context'; import ThemedButton from './themed-button'; // 一个使用 ThemedButton 的中间组件 function Toolbar(props) { return ( <ThemedButton onClick={props.changeTheme}> Change Theme </ThemedButton> ); } class App extends React.Component { constructor(props) { super(props); this.state = { theme: themes.light, }; this.toggleTheme = () => { this.setState(state => ({ theme: state.theme === themes.dark ? themes.light : themes.dark, })); }; } render() { // 在 ThemeProvider 内部的 ThemedButton 按钮组件使用 state 中的 theme 值, // 而外部的组件使用默认的 theme 值 return ( <Page> <ThemeContext.Provider value={this.state.theme}> <Toolbar changeTheme={this.toggleTheme} /> </ThemeContext.Provider> <Section> <ThemedButton /> </Section> </Page> ); } } ReactDOM.render(<App />, document.root); // 使用ThemeContext.Provider包裹的组件,可以消费到ThemeContext中的value // 即Toolbar、ThemedButton中都可以使用this.context来获取到value // 注意观察,更新state的方法是通过props向下传递,由子孙组件触发更新,下面会讲到通过context的方式传递更新函数
value
값은 구성 요소 트리에서 이 컨텍스트에 가장 가까운 공급자가 제공한 value
값과 동일합니다. 해당 공급자가 없는 경우 value
매개변수는 createContext()
에 전달된 defaultValue
와 동일합니다.
Context.displayName
컨텍스트 개체는 문자열 유형인 displayName
이라는 속성을 허용합니다. React DevTools는 이 문자열을 사용하여 표시할 컨텍스트를 결정합니다.
다음 구성 요소는 DevTools에서 MyDisplayName으로 표시됩니다// 确保传递给 createContext 的默认值数据结构是调用的组件(consumers)所能匹配的!
export const ThemeContext = React.createContext({
theme: themes.dark,
toggleTheme: () => {}, // 定义更新主题的方法,向下传递
});
import { ThemeContext } from './theme-context'; function ThemeTogglerButton() { // Theme Toggler 按钮不仅仅只获取 theme 值,它也从 context 中获取到一个 toggleTheme 函数(下面app.js部分) return ( <ThemeContext.Consumer> {({theme, toggleTheme}) => ( <button onClick={toggleTheme} style={{backgroundColor: theme.background}}> Toggle Theme </button> )} </ThemeContext.Consumer> ); } export default ThemeTogglerButton;
import { ThemeContext, themes } from './theme-context'; import ThemeTogglerButton from './theme-toggler-button'; class App extends React.Component { constructor(props) { super(props); this.toggleTheme = () => { this.setState(state => ({ theme: state.theme === themes.dark ? themes.light : themes.dark, })); }; // State 也包含了更新函数,因此它会被传递进 context provider。 this.state = { theme: themes.light, toggleTheme: this.toggleTheme, // 定义更新函数,通过context方式向下传递 }; } render() { // 整个 state 都被传递进 provider return ( <ThemeContext.Provider value={this.state}> <Content /> </ThemeContext.Provider> ); } } function Content() { return ( <p> <ThemeTogglerButton /> </p> ); } ReactDOM.render(<App />, document.root);
import { ThemeContext, themes } from './theme-context'; import ThemedButton from './themed-button'; // 一个使用 ThemedButton 的中间组件 function Toolbar(props) { return ( <ThemedButton onClick={props.changeTheme}> Change Theme </ThemedButton> ); } class App extends React.Component { constructor(props) { super(props); this.state = { theme: themes.light, }; this.toggleTheme = () => { this.setState(state => ({ theme: state.theme === themes.dark ? themes.light : themes.dark, })); }; } render() { // 在 ThemeProvider 内部的 ThemedButton 按钮组件使用 state 中的 theme 值, // 而外部的组件使用默认的 theme 值 return ( <Page> <ThemeContext.Provider value={this.state.theme}> <Toolbar changeTheme={this.toggleTheme} /> </ThemeContext.Provider> <Section> <ThemedButton /> </Section> </Page> ); } } ReactDOM.render(<App />, document.root); // 使用ThemeContext.Provider包裹的组件,可以消费到ThemeContext中的value // 即Toolbar、ThemedButton中都可以使用this.context来获取到value // 注意观察,更新state的方法是通过props向下传递,由子孙组件触发更新,下面会讲到通过context的方式传递更新函数
在嵌套组件中更新 Context
在上面的例子中,我们通过 props 的方式向下传递一个更新函数,从而改变 App 中 themes 的值。我们知道,从一个在组件树中嵌套很深的组件中更新 context 是很有必要的。在这种场景下,你可以通过 context 传递一个函数,使得 consumers 组件更新 context
theme-context.js
// 确保传递给 createContext 的默认值数据结构是调用的组件(consumers)所能匹配的! export const ThemeContext = React.createContext({ theme: themes.dark, toggleTheme: () => {}, // 定义更新主题的方法,向下传递 });
theme-toggler-button.js
import { ThemeContext } from './theme-context'; function ThemeTogglerButton() { // Theme Toggler 按钮不仅仅只获取 theme 值,它也从 context 中获取到一个 toggleTheme 函数(下面app.js部分) return ( <ThemeContext.Consumer> {({theme, toggleTheme}) => ( <button onClick={toggleTheme} style={{backgroundColor: theme.background}}> Toggle Theme </button> )} </ThemeContext.Consumer> ); } export default ThemeTogglerButton;
app.js
import { ThemeContext, themes } from './theme-context'; import ThemeTogglerButton from './theme-toggler-button'; class App extends React.Component { constructor(props) { super(props); this.toggleTheme = () => { this.setState(state => ({ theme: state.theme === themes.dark ? themes.light : themes.dark, })); }; // State 也包含了更新函数,因此它会被传递进 context provider。 this.state = { theme: themes.light, toggleTheme: this.toggleTheme, // 定义更新函数,通过context方式向下传递 }; } render() { // 整个 state 都被传递进 provider return ( <ThemeContext.Provider value={this.state}> <Content /> </ThemeContext.Provider> ); } } function Content() { return ( <p> <ThemeTogglerButton /> </p> ); } ReactDOM.render(<App />, document.root);
消费多个 Context
为了确保 context 快速进行重渲染,React 需要使每一个 consumers 组件的 context 在组件树中成为一个单独的节点
// Theme context,默认的 theme 是 "light" 值 const ThemeContext = React.createContext('light'); // 用户登录 context const UserContext = React.createContext({ name: 'Guest', }); class App extends React.Component { render() { const { signedInUser, theme } = this.props; // 提供初始 context 值的 App 组件 return ( <ThemeContext.Provider value={theme}> <UserContext.Provider value={signedInUser}> <Layout /> </UserContext.Provider> </ThemeContext.Provider> ); } } function Layout() { return ( <p> <Sidebar /> <Content /> </p> ); } // 一个组件可能会消费多个 context function Content() { return ( <ThemeContext.Consumer> {theme => ( <UserContext.Consumer> {user => ( <ProfilePage user={user} theme={theme} /> )} </UserContext.Consumer> )} </ThemeContext.Consumer> ); }
如果两个或者更多的 context 值经常被一起使用,那你可能要考虑一下另外创建你自己的渲染组件,以提供这些值。
注意事项
因为 context 会使用参考标识(reference identity)来决定何时进行渲染,这里可能会有一些陷阱,当 provider 的父组件进行重渲染时,可能会在 consumers 组件中触发意外的渲染。举个例子,当每一次 Provider 重渲染时,以下的代码会重渲染所有下面的 consumers 组件,因为 value
属性总是被赋值为新的对象
class App extends React.Component { render() { return ( <MyContext.Provider value={{something: 'something'}}> <Toolbar /> </MyContext.Provider> ); } }
为了防止这种情况,将 value 状态提升到父节点的 state 里
class App extends React.Component { constructor(props) { super(props); // 多次渲染,state 会被保留,当value不变时,下面的 consumers 组件不会重新渲染 this.state = { value: {something: 'something'}, }; } render() { return ( <Provider value={this.state.value}> <Toolbar /> </Provider> ); } }
【相关推荐:javascript视频教程、web前端】
위 내용은 반응의 맥락은 무엇입니까의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











React와 WebSocket을 사용하여 실시간 채팅 애플리케이션을 구축하는 방법 소개: 인터넷의 급속한 발전과 함께 실시간 커뮤니케이션이 점점 더 주목을 받고 있습니다. 실시간 채팅 앱은 현대 사회 생활과 직장 생활에서 필수적인 부분이 되었습니다. 이 글에서는 React와 WebSocket을 사용하여 간단한 실시간 채팅 애플리케이션을 구축하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. 기술적 준비 실시간 채팅 애플리케이션 구축을 시작하기 전에 다음과 같은 기술과 도구를 준비해야 합니다. React: 구축을 위한 것

React 프론트엔드와 백엔드 분리 가이드: 프론트엔드와 백엔드 분리 및 독립적 배포를 달성하는 방법, 구체적인 코드 예제가 필요합니다. 오늘날의 웹 개발 환경에서는 프론트엔드와 백엔드 분리가 추세가 되었습니다. . 프런트엔드 코드와 백엔드 코드를 분리함으로써 개발 작업을 보다 유연하고 효율적으로 수행하고 팀 협업을 촉진할 수 있습니다. 이 기사에서는 React를 사용하여 프런트엔드와 백엔드 분리를 달성하고 이를 통해 디커플링 및 독립적 배포 목표를 달성하는 방법을 소개합니다. 먼저 프론트엔드와 백엔드 분리가 무엇인지 이해해야 합니다. 전통적인 웹 개발 모델에서는 프런트엔드와 백엔드가 결합되어 있습니다.

React와 Flask를 사용하여 간단하고 사용하기 쉬운 웹 애플리케이션을 구축하는 방법 소개: 인터넷의 발전과 함께 웹 애플리케이션의 요구 사항은 점점 더 다양해지고 복잡해지고 있습니다. 사용 편의성과 성능에 대한 사용자 요구 사항을 충족하기 위해 최신 기술 스택을 사용하여 네트워크 애플리케이션을 구축하는 것이 점점 더 중요해지고 있습니다. React와 Flask는 프런트엔드 및 백엔드 개발을 위한 매우 인기 있는 프레임워크이며, 함께 잘 작동하여 간단하고 사용하기 쉬운 웹 애플리케이션을 구축합니다. 이 글에서는 React와 Flask를 활용하는 방법을 자세히 설명합니다.

React 및 RabbitMQ를 사용하여 안정적인 메시징 애플리케이션을 구축하는 방법 소개: 최신 애플리케이션은 실시간 업데이트 및 데이터 동기화와 같은 기능을 달성하기 위해 안정적인 메시징을 지원해야 합니다. React는 사용자 인터페이스 구축을 위한 인기 있는 JavaScript 라이브러리인 반면 RabbitMQ는 안정적인 메시징 미들웨어입니다. 이 기사에서는 React와 RabbitMQ를 결합하여 안정적인 메시징 애플리케이션을 구축하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. RabbitMQ 개요:

React 반응형 디자인 가이드: 적응형 프런트엔드 레이아웃 효과를 달성하는 방법 모바일 장치의 인기와 멀티스크린 경험에 대한 사용자 요구가 증가함에 따라 반응형 디자인은 현대 프런트엔드 개발에서 중요한 고려 사항 중 하나가 되었습니다. 현재 가장 인기 있는 프런트 엔드 프레임워크 중 하나인 React는 개발자가 적응형 레이아웃 효과를 달성하는 데 도움이 되는 풍부한 도구와 구성 요소를 제공합니다. 이 글에서는 React를 사용하여 반응형 디자인을 구현하는 데 대한 몇 가지 지침과 팁을 공유하고 참조할 수 있는 구체적인 코드 예제를 제공합니다. React를 사용한 Fle

React 코드 디버깅 가이드: 프런트엔드 버그를 빠르게 찾고 해결하는 방법 소개: React 애플리케이션을 개발할 때 애플리케이션을 충돌시키거나 잘못된 동작을 유발할 수 있는 다양한 버그에 자주 직면하게 됩니다. 따라서 디버깅 기술을 익히는 것은 모든 React 개발자에게 필수적인 능력입니다. 이 기사에서는 프런트엔드 버그를 찾고 해결하기 위한 몇 가지 실용적인 기술을 소개하고 독자가 React 애플리케이션에서 버그를 빠르게 찾고 해결하는 데 도움이 되는 특정 코드 예제를 제공합니다. 1. 디버깅 도구 선택: In Re

ReactRouter 사용자 가이드: 프런트엔드 라우팅 제어 구현 방법 단일 페이지 애플리케이션의 인기로 인해 프런트엔드 라우팅은 무시할 수 없는 중요한 부분이 되었습니다. React 생태계에서 가장 널리 사용되는 라우팅 라이브러리인 ReactRouter는 풍부한 기능과 사용하기 쉬운 API를 제공하여 프런트 엔드 라우팅 구현을 매우 간단하고 유연하게 만듭니다. 이 기사에서는 ReactRouter를 사용하는 방법을 소개하고 몇 가지 구체적인 코드 예제를 제공합니다. ReactRouter를 먼저 설치하려면 다음이 필요합니다.

React와 Google BigQuery를 사용하여 빠른 데이터 분석 애플리케이션을 구축하는 방법 소개: 오늘날 정보 폭발 시대에 데이터 분석은 다양한 산업에서 없어서는 안 될 연결 고리가 되었습니다. 그중에서도 빠르고 효율적인 데이터 분석 애플리케이션을 구축하는 것은 많은 기업과 개인이 추구하는 목표가 되었습니다. 이 기사에서는 React와 Google BigQuery를 사용하여 빠른 데이터 분석 애플리케이션을 구축하는 방법을 소개하고 자세한 코드 예제를 제공합니다. 1. 개요 React는 빌드를 위한 도구입니다.
