如何在使用 Hooks 的 React 函数中编写 switch case

瓦姆西

我正在开发一个 React 项目,因为我有一个按钮,对于那个按钮,我编写了一个更改背景颜色的函数,但是我真正需要的是当设备大小为 320px 时,当我单击按钮时,它的背景颜色必须更改为红色。同样,如果设备大小为 768 像素,那么当我单击按钮时,其背景颜色必须更改为绿色。为此,我正在尝试使用 switch case,但我不知道如何在函数中编写 switch case,所以请帮助我实现这一目标

这是我的代码

这是 App.js

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, '***')
    setBackGroundColor({
      backgroundColor: 'red'
    })
    switch (deviceSize === 320) {
      
    }
  }

  useEffect(() => {
  }, [])

  
  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

如果您有任何问题,请告诉我。谢谢

越南的

如果你想要 switch case,你可以这样做:

switch (deviceSize) {
  case 320: 
    setBackGroundColor({
      backgroundColor: 'red'
    });
    break;
  case 768: 
    setBackGroundColor({
      backgroundColor: 'green'
    });
    break;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章