import React, {Component, useState, useEffect} from 'react';
import {connect} from 'react-redux';
import BigHeader from './bigHeader';
import SmallHeader from './smallHeader';
function isSmall() {
if(this.windowWidth < 1307){
return true;
}
return false;
}
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
function determineWidth() {
const width = window.innerWidth;
setWindowWidth(width);
isSmall(width);
}
useEffect(() => {
window.addEventListener("resize", determineWidth);
return function() {
window.removeEventListener("resize", determineWidth);
}
})
class Header extends Component {
render() {
return this.isSmall() ? <SmallHeader/> : <BigHeader/>
}
}
// export default connect(mapStateToProps, page);
export default Header;
我从这一行收到错误const [windowWidth, setWindowWidth] = useState(window.innerWidth);
当屏幕<1307 时,我正在尝试返回一个移动/较小的标头,并在高于该标题时返回不同的标头。
如果你想使用钩子(包括自定义钩子(,你必须从功能组件中使用它们,下面是带有自定义钩子的代码,Header 是一个功能组件而不是一个类:
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import BigHeader from './bigHeader';
import SmallHeader from './smallHeader';
const useWindowWidth = () => {
function determineWidth() {
const width = window.innerWidth;
setWindowWidth(width);
}
const [windowWidth, setWindowWidth] = useState(
window.innerWidth
);
useEffect(() => {
window.addEventListener('resize', determineWidth);
return function() {
window.removeEventListener('resize', determineWidth);
};
},[]);
return windowWidth;
};
function useIsSmall() {
const windowWidth = useWindowWidth();
if (windowWidth < 1307) {
return true;
}
return false;
}
function Header(props) {
const isSmall = useIsSmall();
return isSmall ? <SmallHeader /> : <BigHeader />;
}
// export default connect(mapStateToProps, page);
export default Header;
您不能在函数外部使用hooks
。
您能否将代码const [windowWidth, setWindowWidth] = useState(window.innerWidth);
移动到函数中,然后尝试一下。
尝试使用 React Native 的 Dimensions,这段代码应该可以工作: 您也可以在每次调用函数isSmall((时更新windowWidth值:
import { Dimensions } from 'react-native'
const windowWidth = Dimensions.get('window').width;
const windowheight = Dimensions.get('window').height;
function isSmall() {
if(this.windowWidth < 1307){
return true;
}
return false;
}
class Header extends Component {
render() {
return this.isSmall() ? <SmallHeader/> : <BigHeader/>
}
}
// export default connect(mapStateToProps, page);
export default Header;
根据 React 文档:Hooks,hooks
只能在功能组件内部使用
大致像这样
import React, { useState } from 'react';
import { Dimensions } from 'react-native'
const windowWidth = Dimensions.get('window').width;
const windowheight = Dimensions.get('window').height;
function Example() {
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
//Return something
return (
<div>
</div>
);
}