参考链接: 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
};
国际化实现思路:
- 通过Context实现;
- 通过在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