React Native : undefined 不是对象 (评估 '_useContext.width')



我想为不同的屏幕尺寸创建一个可重用的代码。我正在使用createContext API,这样我就不会在不同的屏幕上重写代码。我得到了这个错误

null is not an object (evaluating '_useContext.width)

顺便说一句,我使用的useWindowDimensions()从reactnative https://reactnative.dev/docs/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')

相关内容

最新更新