您好,登錄后才能下訂單哦!
要在React項目中實(shí)現主題切換并持久化用戶(hù)偏好設置,可以按照以下步驟進(jìn)行:
import React, { useState } from 'react';
const ThemeManager = () => {
const [theme, setTheme] = useState(localStorage.getItem('theme') || 'light');
const toggleTheme = () => {
const newTheme = theme === 'light' ? 'dark' : 'light';
setTheme(newTheme);
localStorage.setItem('theme', newTheme);
};
return (
<div>
<button onClick={toggleTheme}>Toggle Theme</button>
<p>Current Theme: {theme}</p>
</div>
);
};
export default ThemeManager;
theme
變量來(lái)應用主題樣式。import React from 'react';
import ThemeManager from './ThemeManager';
const App = () => {
return (
<div>
<ThemeManager />
<div className="content">
<h1>Theme Switcher Demo</h1>
<p>This is a sample text</p>
</div>
</div>
);
};
export default App;
// styles.scss
.light {
background-color: #f0f0f0;
color: #333;
}
.dark {
background-color: #333;
color: #f0f0f0;
}
// App.js
import React from 'react';
import ThemeManager from './ThemeManager';
import './styles.scss';
const App = () => {
return (
<div className={`app ${localStorage.getItem('theme') || 'light'}`}>
<ThemeManager />
<div className="content">
<h1>Theme Switcher Demo</h1>
<p>This is a sample text</p>
</div>
</div>
);
};
export default App;
通過(guò)以上步驟,你可以在React項目中實(shí)現主題切換并持久化用戶(hù)偏好設置。當用戶(hù)切換主題時(shí),應用會(huì )動(dòng)態(tài)改變樣式,并且用戶(hù)的偏好設置會(huì )被保存在本地存儲中,以便下次訪(fǎng)問(wèn)時(shí)重新加載。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系站長(cháng)郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。