栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用React重新调整浏览器的渲染视图

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用React重新调整浏览器的渲染视图

使用React Hooks:

您可以定义一个自定义的Hook来监听window

resize
事件,如下所示:

import React, { useLayoutEffect, useState } from 'react';function useWindowSize() {  const [size, setSize] = useState([0, 0]);  useLayoutEffect(() => {    function updateSize() {      setSize([window.innerWidth, window.innerHeight]);    }    window.addEventListener('resize', updateSize);    updateSize();    return () => window.removeEventListener('resize', updateSize);  }, []);  return size;}function ShowWindowDimensions(props) {  const [width, height] = useWindowSize();  return <span>Window size: {width} x {height}</span>;}

这样做的好处是逻辑被封装,您可以在要使用窗口大小的任何位置使用此Hook。

使用React类:

您可以在componentDidMount中进行监听,类似于该组件,它仅显示窗口尺寸(如

<span>Window size: 1024 x768</span>
):

import React from 'react';class ShowWindowDimensions extends React.Component {  state = { width: 0, height: 0 };  render() {    return <span>Window size: {this.state.width} x {this.state.height}</span>;  }  updateDimensions = () => {    this.setState({ width: window.innerWidth, height: window.innerHeight });  };  componentDidMount() {    window.addEventListener('resize', this.updateDimensions);  }  componentWillUnmount() {    window.removeEventListener('resize', this.updateDimensions);  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485100.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号