React(11)-全局共享通信Context
warning:
这篇文章距离上次修改已过186天,其中的内容可能已经有所变动。
import React from 'react';
// 创建一个Context对象
const GlobalContext = React.createContext();
// 创建一个提供全局状态的组件
class GlobalProvider extends React.Component {
state = {
globalState: {
isLoggedIn: false,
user: null
},
setGlobalState: (newGlobalState) => {
this.setState(prevState => ({
globalState: { ...prevState.globalState, ...newGlobalState }
}));
}
};
render() {
// 使用Provider组件提供全局状态
return (
<GlobalContext.Provider value={this.state}>
{this.props.children}
</GlobalContext.Provider>
);
}
}
// 高阶组件,用于从Context中获取状态和设置状态的函数
const withGlobalContext = (Component) => {
return class extends React.Component {
static displayName = `WithGlobalContext(${Component.displayName || Component.name})`;
render() {
return (
<GlobalContext.Consumer>
{context => <Component {...this.props} globalContext={context} />}
</GlobalContext.Consumer>
);
}
};
};
export { GlobalProvider, withGlobalContext };
这段代码定义了一个全局状态的Context,并提供了一个GlobalProvider组件来管理全局状态,以及一个高阶组件withGlobalContext用于将全局状态和设置状态的函数注入到需要它们的组件中。这样,应用中的任何组件都可以通过这种方式来访问和修改全局状态。
评论已关闭