Gatsby 是一个静态站点生成器,它使用 React 作为其核心库。createPage
是 Gatsby 的一个 API,用于在构建时创建页面。React 上下文(Context)提供了一种在组件树中共享数据的方式,而不需要手动通过 props 传递数据。
React 上下文主要有两种类型:
当需要在多个组件间共享数据时,可以使用上下文。例如,主题设置、用户认证信息等。
在 Gatsby 中,你可以在 gatsby-node.js
文件中使用 createPage
API 创建页面,并在 React 组件类中使用上下文。
// src/context/ThemeContext.js
import React from 'react';
const ThemeContext = React.createContext('light');
export default ThemeContext;
// src/components/ThemeProvider.js
import React from 'react';
import ThemeContext from '../context/ThemeContext';
class ThemeProvider extends React.Component {
state = {
theme: 'light',
};
toggleTheme = () => {
this.setState((prevState) => ({
theme: prevState.theme === 'light' ? 'dark' : 'light',
}));
};
render() {
return (
<ThemeContext.Provider value={{ ...this.state, toggleTheme: this.toggleTheme }}>
{this.props.children}
</ThemeContext.Provider>
);
}
}
export default ThemeProvider;
gatsby-browser.js
中使用 Provider:// gatsby-browser.js
import React from 'react';
import ThemeProvider from './src/components/ThemeProvider';
export const wrapRootElement = ({ element }) => (
<ThemeProvider>{element}</ThemeProvider>
);
// src/components/MyComponent.js
import React from 'react';
import ThemeContext from '../context/ThemeContext';
class MyComponent extends React.Component {
static contextType = ThemeContext;
render() {
const { theme, toggleTheme } = this.context;
return (
<div>
<h1>Current Theme: {theme}</h1>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
}
}
export default MyComponent;
原因:Gatsby 是静态站点生成器,页面刷新后,上下文数据没有持久化。
解决方法:
// src/components/ThemeProvider.js
import React from 'react';
import ThemeContext from '../context/ThemeContext';
class ThemeProvider extends React.Component {
state = {
theme: localStorage.getItem('theme') || 'light',
};
toggleTheme = () => {
const newTheme = this.state.theme === 'light' ? 'dark' : 'light';
this.setState({ theme: newTheme });
localStorage.setItem('theme', newTheme);
};
render() {
return (
<ThemeContext.Provider value={{ ...this.state, toggleTheme: this.toggleTheme }}>
{this.props.children}
</ThemeContext.Provider>
);
}
}
export default ThemeProvider;
// gatsby-node.js
exports.createPages = async ({ actions }) => {
const { createPage } = actions;
// 创建页面逻辑...
// 传递上下文数据
createPage({
path: '/my-page',
component: require.resolve('./src/templates/MyPage.js'),
context: {
theme: 'light',
},
});
};
// src/templates/MyPage.js
import React from 'react';
import ThemeContext from '../../context/ThemeContext';
class MyPage extends React.Component {
static contextType = ThemeContext;
render() {
const { theme } = this.context;
return (
<div>
<h1>Current Theme: {theme}</h1>
</div>
);
}
}
export default MyPage;
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云