React中明暗模式切换问题求助:useDarkMode库使用异常
use-dark-mode Library in React I spot the issue in your code immediately — you're checking the entire darkMode object returned by the hook instead of its actual boolean state value. Let's fix this step by step:
Step 1: Correct the State Check
The useDarkMode hook returns an object with properties like value (the current dark mode state), enable, disable, and toggle. Your current condition {darkMode ? ... : ...} is checking if the object exists (which it always does), so it never switches to the moon button. You need to reference darkMode.value instead.
Fixed Code
import useDarkMode from 'use-dark-mode'; const DarkModeToggle = () => { // Initialize with false (light mode as default) const darkMode = useDarkMode(false); return ( <> {/* Check the actual boolean state with darkMode.value */} {darkMode.value ? ( <button type="button" onClick={darkMode.disable}> ☀ </button> ) : ( <button type="button" onClick={darkMode.enable}> ☾ </button> )} </> ); }; export default DarkModeToggle;
Bonus: Clean Up with the Built-in toggle Method
For simpler code, use the toggle method provided by the hook instead of handling enable/disable separately:
import useDarkMode from 'use-dark-mode'; const DarkModeToggle = () => { const darkMode = useDarkMode(false); return ( <button type="button" onClick={darkMode.toggle}> {darkMode.value ? '☀' : '☾'} </button> ); }; export default DarkModeToggle;
Critical: Set Up Your Theme Styles
Remember that the use-dark-mode library automatically adds a dark class to the <html> element when dark mode is enabled. You need corresponding CSS to actually switch the visual theme, for example:
/* Light mode (default) */ body { background-color: #fff; color: #111; transition: all 0.3s ease; } /* Dark mode */ .dark body { background-color: #111; color: #fff; }
Why Your Custom Hook Attempt Might Have Failed
If you tried building a custom hook earlier, common missteps include:
- Not persisting state to localStorage (the
use-dark-modelibrary handles this out of the box) - Forgetting to sync the state with the
darkclass on the<html>element - Mishandling the toggle logic between boolean states
内容的提问来源于stack exchange,提问作者helpmepie

