React에서 컨텍스트는 컴포넌트의 각 레이어에 대한 props를 수동으로 추가하지 않고 컴포넌트 트리 간에 데이터를 전송하는 방법입니다. 컨텍스트는 컴포넌트 트리를 통해 레이어별로 props를 명시적으로 전달할 필요 없이 컴포넌트 간에 지정된 값을 공유하는 방법을 제공합니다. .
이 튜토리얼의 운영 환경: Windows 10 시스템, 반응 버전 17.0.1, Dell G3 컴퓨터.
React에서 컨텍스트란 무엇인가요?
컨텍스트는 각 구성 요소 레이어에 소품을 수동으로 추가하지 않고도 구성 요소 트리 간에 데이터를 전송하는 방법을 제공합니다. 일반적인 React 애플리케이션에서 데이터는 props를 통해 위에서 아래로(상위에서 하위로) 전달되지만 이 접근 방식은 특정 유형의 속성(예: 로케일 기본 설정, UI 테마)에 대해 매우 번거롭습니다. 응용 프로그램. 컨텍스트는 컴포넌트 트리의 각 레벨을 통해 props를 명시적으로 전달하지 않고도 컴포넌트 간에 이러한 값을 공유할 수 있는 방법을 제공합니다.
Context 언제 사용하나요?
컨텍스트는 현재 인증된 사용자, 테마 또는 기본 언어와 같은 구성 요소 트리에 "전역"인 데이터를 공유하도록 설계되었습니다. 예를 들어, 아래 코드에서는 "테마" 속성을 통해 버튼 구성 요소의 스타일을 수동으로 조정합니다
class App extends React.Component { render() { return <toolbar></toolbar>; } } function Toolbar(props) { // Toolbar 组件接受一个额外的“theme”属性,然后传递给 ThemedButton 组件。 // 如果应用中每一个单独的按钮都需要知道 theme 的值,这会是件很麻烦的事, // 因为必须将这个值层层传递所有组件。 return ( <p> <themedbutton></themedbutton> </p> ); } class ThemedButton extends React.Component { render() { return <button></button>; } } // 通过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> <toolbar></toolbar> </themecontext.provider> ); } } // 中间的组件再也不必指明往下传递 theme 了。 function Toolbar() { return ( <p> <themedbutton></themedbutton> </p> ); } class ThemedButton extends React.Component { // 指定 contextType 读取当前的 theme context。 // React 会往上找到最近的 theme Provider,然后使用它的值。 // 在这个例子中,当前的 theme 值为 “dark”。 static contextType = ThemeContext; render() { return <button></button>; } } // 也可以使用 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></mycontext.provider>
每个 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> /* 基于 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 中</mycontext.consumer></mycontext.provider>
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); // 该处为默认值각 Context 개체는 구성 요소를 사용하여 컨텍스트 변경 사항을 구독할 수 있는 Provider React 구성 요소를 반환합니다.
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></button> ); } // 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> 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> <toolbar></toolbar> </themecontext.provider> <section> <themedbutton></themedbutton> </section> </page> ); } } ReactDOM.render(<app></app>, document.root); // 使用ThemeContext.Provider包裹的组件,可以消费到ThemeContext中的value // 即Toolbar、ThemedButton中都可以使用this.context来获取到value // 注意观察,更新state的方法是通过props向下传递,由子孙组件触发更新,下面会讲到通过context的方式传递更新函数여기에서 React 구성 요소는 컨텍스트 변경 사항을 구독할 수도 있습니다. 이를 통해 기능 구성 요소의 컨텍스트를 구독할 수 있습니다. 어린 시절의 기능이 필요합니다. 이 함수는 현재 컨텍스트 값을 수신하고 React 노드를 반환합니다. 함수에 전달된
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> Toggle Theme </button> )} </themecontext.consumer> ); } export default ThemeTogglerButton;🎜🎜themed-button.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> <content></content> </themecontext.provider> ); } } function Content() { return ( <p> <themetogglerbutton></themetogglerbutton> </p> ); } ReactDOM.render(<app></app>, document.root);🎜🎜app.js🎜🎜
import { ThemeContext, themes } from './theme-context'; import ThemedButton from './themed-button'; // 一个使用 ThemedButton 的中间组件 function Toolbar(props) { return ( <themedbutton> 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> <toolbar></toolbar> </themecontext.provider> <section> <themedbutton></themedbutton> </section> </page> ); } } ReactDOM.render(<app></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> 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> <content></content> </themecontext.provider> ); } } function Content() { return ( <p> <themetogglerbutton></themetogglerbutton> </p> ); } ReactDOM.render(<app></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> <usercontext.provider> <layout></layout> </usercontext.provider> </themecontext.provider> ); } } function Layout() { return ( <p> <sidebar></sidebar> <content></content> </p> ); } // 一个组件可能会消费多个 context function Content() { return ( <themecontext.consumer> {theme => ( <usercontext.consumer> {user => ( <profilepage></profilepage> )} </usercontext.consumer> )} </themecontext.consumer> ); }
如果两个或者更多的 context 值经常被一起使用,那你可能要考虑一下另外创建你自己的渲染组件,以提供这些值。
注意事项
因为 context 会使用参考标识(reference identity)来决定何时进行渲染,这里可能会有一些陷阱,当 provider 的父组件进行重渲染时,可能会在 consumers 组件中触发意外的渲染。举个例子,当每一次 Provider 重渲染时,以下的代码会重渲染所有下面的 consumers 组件,因为 value
属性总是被赋值为新的对象
class App extends React.Component { render() { return ( <mycontext.provider> <toolbar></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> <toolbar></toolbar> </provider> ); } }
【相关推荐:javascript视频教程、web前端】
위 내용은 반응의 맥락은 무엇입니까의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

React는 핵심 구성 요소 및 상태 관리 기능을 갖춘 사용자 인터페이스를 구축하기위한 JavaScript 라이브러리입니다. 1) 구성 요소화 및 상태 관리를 통해 UI 개발을 단순화합니다. 2) 작업 원칙에는 화해 및 렌더링이 포함되며 최적화는 React.Memo 및 Usememo를 통해 구현할 수 있습니다. 3) 기본 사용법은 구성 요소를 작성하고 렌더링하는 것입니다. 고급 사용법에는 후크 및 컨텍스트를 사용하는 것이 포함됩니다. 4) 부적절한 상태 업데이트와 같은 일반적인 오류는 ReactDevTools를 사용하여 디버그 할 수 있습니다. 5) 성능 최적화에는 React.Memo, 가상화 목록 및 코드플릿을 사용하는 것이 포함되며 코드를 읽을 수 있고 유지 관리 가능하게 유지하는 것이 가장 좋습니다.

React는 JSX와 HTML을 결합하여 사용자 경험을 향상시킵니다. 1) JSX는 개발을보다 직관적으로 만들기 위해 HTML을 포함시킨다. 2) 가상 DOM 메커니즘은 성능을 최적화하고 DOM 운영을 줄입니다. 3) 유지 보수성을 향상시키기위한 구성 요소 기반 관리 UI. 4) 상태 관리 및 이벤트 처리는 상호 작용을 향상시킵니다.

반응 구성 요소는 함수 또는 클래스로 정의 할 수 있으며 UI 로직을 캡슐화하고 소품을 통해 입력 데이터를 수락합니다. 1) 구성 요소 정의 : 기능 또는 클래스를 사용하여 반응 요소를 반환합니다. 2) 렌더링 구성 요소 : 반응 호출 렌더 메소드 또는 기능 구성 요소를 실행합니다. 3) 멀티플렉싱 구성 요소 : 소품을 통해 데이터를 전달하여 복잡한 UI를 구축합니다. 구성 요소의 수명주기 접근 방식을 통해 다른 단계에서 논리를 실행하여 개발 효율성 및 코드 유지 관리 가능성을 향상시킬 수 있습니다.

React Strict Mode는 추가 점검 및 경고를 활성화하여 React 응용 프로그램의 잠재적 문제를 강조하는 개발 도구입니다. 레거시 코드, 안전하지 않은 라이프 사이클 및 부작용을 식별하여 현대 반응 관행을 장려합니다.

반응 단편은 추가 DOM 노드없이 어린이를 그룹화하고 구조, 성능 및 접근성을 향상시킬 수 있습니다. 효율적인 목록 렌더링을위한 키를 지원합니다.

이 기사에서는 React의 조정 프로세스가 DOM을 효율적으로 업데이트하는 방법에 대해 자세히 설명합니다. 주요 단계에는 조정 트리거, 가상 DOM 생성, 차이 알고리즘 사용 및 최소 DOM 업데이트 적용이 포함됩니다. Perfo도 다룹니다

이 기사는 직접 DOM 조작을 최소화하고 업데이트를 최적화하여 성능을 향상시키는 웹 개발의 핵심 개념 인 Virtual DOM에 대해 설명합니다.

이 기사는 소프트웨어 개발의 요소와 구성 요소의 차이점에 대해 논의하여 역할, 차이 및 프로젝트 관리에 미치는 영향을 강조합니다. 주요 문제는 사용자 interfac 내의 복잡성, 재사용 및 기능이 포함됩니다.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

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

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

뜨거운 주제



