reactjs - react ,状态变化没有反射(reflect)在回调函数中

我是 React 的新手,偶然发现了一个我不理解也无法解决的问题。 我想在特定窗口屏幕宽度阈值交叉时动态更改内部 block 大小。

这是我准备的示例代码:

function X(title) {
  const [myWidth, setMyWidth] = React.useState(200)   
  
  function onResize(){
    if(innerWidth > 1000 && myWidth <= 200){
      console.log(`Make Bigger: `, myWidth)
      setMyWidth(400)
    } else if( innerWidth <= 1000 && myWidth >= 400) {
      console.log(`Make Smaller: `, myWidth)
      setMyWidth(200)
    }
  }
  
  React.useEffect(()=>{
    console.log("HELLO")
    addEventListener('resize', onResize)
  },[])
  
  return (<div>
      <div style={{
          backgroundColor:'red',
          width: myWidth,
          height: 100
        }}>
        Hello
      </div>
    </div>);
}

const el = document.querySelector("#root");
ReactDOM.render(<X title='Example Component' />, el);

我想看到 div block 宽度在 innerWidth 大于 1000 时增加,而在 innerWidth 小于 1000 时减小 BUT我不想在每次监听器回调调用时都看到控制台消息(即屏幕宽度的每个像素变化)。

https://codepen.io/radoslavmarino7/pen/KKoYNWK?editors=0011

最佳答案

可能使用媒体查询方法会更好。

检查这个简单的实现。

.box {
  background: red;
  height: 100px;
  display: block;
}

@media only screen and (max-width: 1000px) {
  .box {
    width: 200px;
  }
}

@media only screen and (min-width: 1000px) {
  .box {
    width: 400px;
  }
}
<div class="box"></div>

CodePen

Documentation

这是React 方法,您应该包括useEffect 依赖项,如下所示:

React.useEffect(()=>{
    console.log("HELLO")
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('resize', onResize);
    };
  },[myWidth, setMyWidth])

CodePen

Documentation

关于reactjs - react ,状态变化没有反射(reflect)在回调函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73465056/

相关文章:

android - 如何在 Jetpack Compose Material 3 中制作 cradl

c# - 在不跳过 OutputFormatter 的情况下捕获异常并使用自定义消息进行响应

javascript - 类型错误 : Cannot read properties of unde

.net - 如何写入 Windows 事件查看器应用程序 channel ? (。网)

xcode - 错误构建 : Command PhaseScriptExecution failed

postgresql - 错误 : connect ECONNREFUSED 127. 0.1.1:

android - 在 Stripe 付款上显示每小时价格而不是存款价格

android - Proguard R8 警告

swift - 填充颜​​色影响 SwiftUI 中的阴影

javascript - 如何从脚本标签和/或控制台中抓取值