我正在开发聊天界面,并希望当窗口大小调整时我的聊天日志项目能够适合屏幕。对于主列表,我使用 FlatList
并且每个单独的项目都是一个单独的组件。
为了实现此目的,我使用 window.addEventLister
方法订阅了 resize
和 fullscreenchange
事件,但在许多情况下仍然无法调整大小例如离开或进入 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/