我想建立一个组件,允许我有不同的按钮大小与react-native-elements
。为了实现这一点,我建立了一个自定义组件,其中有一个属性size
,并与此我动态访问到一个特定大小的按钮与其各自的样式内theme
对象。一切工作正常,如预期,但我有以下错误的typescript:TS2532: Object is possibly 'undefined'.
,每次我尝试访问theme
中的sizes
对象时,使用括号表示法。
自定义按钮组件
import React, { useContext } from 'react';
import { Button, FullTheme, ThemeContext } from 'react-native-elements';
export type Props = Button['props'];
export type Theme = Partial<FullTheme>;
const styles = {
button: (theme: Partial<FullTheme>, size: string) => ({
padding: theme?.Button?.sizes[size]?.padding, // problem here
}),
title: (theme: Partial<FullTheme>, size: string) => ({
fontSize: theme?.Button?.sizes[size]?.fontSize, // problem here
lineHeight: theme?.Button?.sizes[size]?.lineHeight, // problem here
fontFamily: theme?.Button?.font?.fontFamily,
}),
};
function ButtonElement(props: Props): JSX.Element {
const {
size = 'medium',
children,
...rest
} = props;
const { theme } = useContext(ThemeContext);
return (
<Button
titleStyle={styles.title(theme, size)}
buttonStyle={styles.button(theme, size)}
{...rest}
>
{children}
</Button>
);
}
主题.ts
export const theme = {
Button: {
font: {
fontFamily: 'inter-display-bold',
},
sizes: {
small: {
fontSize: 14,
padding: 10,
lineHeight: 20,
},
medium: {
fontSize: 18,
padding: 14,
lineHeight: 24,
},
large: {
fontSize: 20,
padding: 18,
lineHeight: 24,
},
},
},
}
// react-native-elements.d.ts -> Extending the default theme to manage button sizes
import 'react-native-elements';
import { StyleProp, TextStyle } from 'react-native';
export type Sizes = {[index: string]: TextStyle};
export type Size = 'small' | 'medium' | 'large';
declare module 'react-native-elements' {
export interface ButtonProps {
font?: TextStyle;
sizes?: Sizes;
size?: Size;
}
export interface FullTheme {
Button: Partial<ButtonProps>;
}
}
将theme
对象传递到组件树
// pass theme to the component tree
import { theme } from '@common/styles/theme';
export default function App(): JSX.Element | null {
return (
<ThemeProvider theme={theme}>
<SafeAreaProvider>
<Navigation />
<StatusBar />
</SafeAreaProvider>
</ThemeProvider>
);
}
1条答案
按热度按时间goqiplq21#
TS2532: Object is possibly 'undefined'
每次我尝试访问主题内的带括号符号的sizes对象时。这很有趣,因为唯一不用the optional chaining operator的地方是在
sizes
字段之后。您有两种选择:
1.如果您知道
sizes
字段永远不会为空、未定义或不存在,那么您可以使用TypeScript的非空Assert类型操作符(仅适用于编译时类型系统)。1.尝试执行
theme?.Button?.sizes?[size]?.fontSize
(运行时操作)。