gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:03:10 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com