问题描述
我想构建一个组件,允许我使用 react-native-elements
拥有不同的按钮大小。为了实现这一点,我构建了一个具有属性 size
的自定义组件,并通过它动态访问特定大小的按钮,并在 theme
对象中使用其各自的样式。一切都按预期工作,但我在打字稿中出现以下错误:TS2532: Object is possibly 'undefined'.
每次我尝试使用括号表示法访问 sizes
内的 theme
对象。
自定义按钮组件
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>
);
}
theme.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,}
// 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>
);
}
我尝试了什么
解决方法
尝试做theme?.Button?.sizes?[size]?.fontSize
。您已将按钮和标题函数的主题参数注释为 Partial<FullTheme>
类型。 Partial<>
用于指示每个成员可能未定义。如果前面的变量在运行时未定义,则使用 optional chaining operator 将表达式短路为未定义。
如果你知道运行时在theme?.Button?.sizes[size]?.fontSize
中成员访问的整个路径,那么你可以用感叹号代替问号。感叹号是 TypeScript 的 non-null assertion type-operator。这是一个编译时概念。