React Hooks中如何在函数内编写switch case实现响应式按钮背景色切换
React 按钮根据视口宽度切换背景色实现方案
核心修改点
- 修正
switch case的参数写法,直接以视口宽度作为匹配条件 - 新增窗口大小变化监听,动态更新当前视口宽度值
- 统一背景色设置逻辑,移除冗余的默认赋值代码
完整可运行代码
import React, { useState, useEffect } from 'react'; import './App.css'; const App = () => { const [backGroundColor, setBackGroundColor] = useState(null) const [deviceSize, changeDeviceSize] = useState(window.innerWidth); const changeBackGroundColor = () => { console.log(deviceSize, '***') let targetColor = '' // 匹配固定宽度场景 switch (deviceSize) { case 320: targetColor = 'red' break case 768: targetColor = 'green' break default: // 其他宽度默认保留btn-primary原生蓝色,可根据需求修改 targetColor = '#0d6efd' break } // 如果是需要匹配宽度范围场景,可替换为以下switch写法 // switch (true) { // case deviceSize <= 320: // targetColor = 'red' // break // case deviceSize <= 768: // targetColor = 'green' // break // default: // targetColor = '#0d6efd' // break // } setBackGroundColor({ backgroundColor: targetColor }) } useEffect(() => { // 监听窗口大小变化,实时更新视口宽度 const handleResize = () => { changeDeviceSize(window.innerWidth) } window.addEventListener('resize', handleResize) // 组件卸载时清除监听,避免内存泄漏 return () => window.removeEventListener('resize', handleResize) }, []) return ( <div className='container'> <div className='row'> <div className='col-12'> <div className='first'> <button onClick={changeBackGroundColor} style={backGroundColor} className='btn btn-primary'>Click here</button> </div> </div> </div> </div> ) } export default App
内容的提问来源于stack exchange,提问作者Vamsi
相关产品推荐
相关产品推荐

