javascript - ReactJS/JavaScript : Not receiving resize event for many cases

标签 javascript reactjs window-resize react-native-web

我正在开发聊天界面,并希望当窗口大小调整时我的聊天日志项目能够适合屏幕。对于主列表,我使用 FlatList 并且每个单独的项目都是一个单独的组件。

为了实现此目的,我使用 window.addEventLister 方法订阅了 resizefullscreenchange 事件,但在许多情况下仍然无法调整大小例如离开或进入 macOS 全屏模式时。

是否还有其他一些我应该订阅或遵循不同方法的事件。有没有一个图书馆可以在一个地方为我提供所有这些类型的事件?

根据请求提供代码片段:

平面 ListView :

export class ChatListItem extends React.Component {

   componentDidMount = () => {
       window.addEventListener("resize", this.forceUpdate);
       window.addEventListener("fullscreenchange", this.forceUpdate);
       //Is there anything wrong with doing it the above way?   
   };

   componentWillUnmount = () => {
       window.removeEventListener("resize", this.forceUpdate);
       window.removeEventListener("fullscreenchange", this.forceUpdate);
   };

   render = () => {
       //My Views which take size using flex:1 / window width and height
   };
}

但是同一个屏幕有一个输入框(由于某种原因我将其制作成不同的组件)并且能够使用相同的逻辑调整大小:

export class ChatInputBox extends React.Component {

   componentDidMount = () => {
       window.addEventListener("resize", this.forceUpdate);
       window.addEventListener("fullscreenchange", this.forceUpdate);
   };

   componentWillUnmount = () => {
       window.removeEventListener("resize", this.forceUpdate);
       window.removeEventListener("fullscreenchange", this.forceUpdate);
   };

   render = () => {
       //My Views which take size using flex:1 / window width and height
   };
}

最佳答案

下面是一个监听屏幕大小调整的 Box 组件。

class Box extends React.Component{
     state = {
         width : window.innerWidth
         height : window.innerHeight
     }

     onResize = () => this.setState({width: window.innerWidth, height: window.innerHeight})

     componentDidMount(){
         window.addEventListener('resize', this.onResize)
     }

     componentWillUnmount(){
         window.removeEventListener('resize', this.onResize)
     }  
    render(){
        const { width, height } = this.state 
        return(
            <div 
                style={{width, height, backgroundColor: 'red}}
            />
        )
    }
}

关于javascript - ReactJS/JavaScript : Not receiving resize event for many cases,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56275156/

相关文章:

java - 调整 JFrame 大小时 Swing 组件抽搐

javascript - 使用 Mocha 和 Chai 断言 Javascript 数组中包含的值

javascript - 在 React 中转换对象的对象

javascript - jquery 偏移顶部错误值,但在页面调整大小时正确

css - 如何使用按钮居中 div (Bootstrap Responsive)

javascript - React Native Android 负边距

javascript - 重试失败的异步/ promise 功能?

c# - 在 C# 中,如何将此数据结构转换为 Json

javascript - 无法加入 QuickBlox 上的对话

javascript - 如何使用 react-table 实现服务器端分页?