React Context上下文

本文探讨了React Context在前端开发中的应用,特别是在实现国际化、主题化等场景中的作用。详细介绍了如何创建和使用Context,包括生产者(Provider)和消费者(Consumer),并讨论了Context的本质和优化策略。
摘要由CSDN通过智能技术生成

参考链接: Context

Context应用场景:

用于全局配置,例如主题化、国际化、大小自适应等需求,需要改变最外层的变量使整个组件树跟着变。

在React中,提供了Context的API,使用方式参考:https://zh-hans.reactjs.org/docs/context.html

在Element UI、Antd中,对React的Context进行了封装,提供了ConfigProvider组件,参考:https://ant.design/components/config-provider-cn

import React from 'react';
import PropTypes from 'prop-types';
import ConfigContext from '../tools/ConfigContext';

export default function ConfigProvider({
     context: Context, children, ...other }) {
   
    return (
        <Context.Consumer>
            {
   config => (
                <Context.Provider value={
   {
    ...config, ...other }}>
                    {
   children}
                </Context.Provider>
            )}
        </Context.Consumer>
    );
}

ConfigProvider.propTypes = {
   
    children: PropTypes.node,
    context: PropTypes.object
};

ConfigProvider.defaultProps = {
   
    children: null,
    context: ConfigContext
};
国际化实现思路:
  1. 通过Context实现;
  2. 通过在webpack的alias上根据不同的环境引入不同的语言包;

Context的引出

官方demo

例如:

class App extends React.Component {
   
  render() {
   
    return <Toolbar theme="dark" />;
  }
}

function Toolbar(props) {
   
  // Toolbar 组件接受一个额外的“theme”属性,然后传递给 ThemedButton 组件。
  // 如果应用中每一个单独的按钮都需要知道 theme 的值,这会是件很麻烦的事,
  // 因为必须将这个值层层传递所有组件。
  return (
    <div>
      <ThemedButton theme={
   props.theme} />
    </div>
  );
}

class ThemedButton extends React.Component {
   
  render() {
   
    return <Button theme={
   this.props.theme} />;
  }
}

上面代码中,需要通过props一层层传递,而使用 context, 我们可以避免通过中间元素传递 props,如下:

// Context 可以让我们无须明确地传遍每一个组件,就能将值深入传递进组件树。
// 为当前的 theme 创建一个 context(“light”为默认值)。
const ThemeContext = React
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

. . . . .

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值