react-native - React Native:未定义不是对象(评估'_useContext.width')
问题描述
我想为不同的屏幕尺寸创建一个可重用的代码。我正在使用 createContext API,这样我就不会在不同的屏幕上重写代码。我收到了这个错误
null is not an object (evaluating '_useContext.width)
顺便说一句,我正在使用 react native https://reactnative.dev/docs/usewindowdimensions中的 useWindowDimensions() 。这是代码。
theme.js
import React, {createContext, useState, useEffect} from 'react';
import {useWindowDimensions} from 'react-native';
export const WindowContext = createContext();
export const DefaultTheme = ({children}) => {
const WIDTH = useWindowDimensions().width;
const HEIGHT = useWindowDimensions().height;
const [width, setWidth] = () => useState(WIDTH);
const [height, setHeight] = () => useState(HEIGHT);
useEffect(() => {
const handleSize = () => setWidth(WIDTH);
setHeight(HEIGHT);
window.addEventListener('resize', handleSize);
return () => window.removeEventListener('resize', handleSize);
}, []);
return (
<WindowContext.Provider
value={{
width: width,
height: height,
}}>
{children}
</WindowContext.Provider>
);
};
我想在我的按钮组件上实现代码
button.js
import React, {useContext} from 'react';
import {WindowContext} from '../../theme';
const Button = ({buttonTitle, textColor, ...rest}) => {
const {width} = useContext(WindowContext);
return (
<>
{width < 376 ? (
<DefaultButton height="50" {...rest}>
<ButtonText color={textColor}>{buttonTitle}</ButtonText>
</DefaultButton>
) : (
<DefaultButton height="60" {...rest}>
<ButtonText color={textColor}>{buttonTitle}</ButtonText>
</DefaultButton>
)}
</>
);
};
export default Button;
解决方案
你可以像这样得到屏幕宽度:
import {Dimensions} from 'react-native';
const { width: screenWidth } = Dimensions.get('window')