将主题传递给函数时,如何解决 TypeScript 错误中可能“未定义”的对象? theme.ts

如何解决将主题传递给函数时,如何解决 TypeScript 错误中可能“未定义”的对象? theme.ts

我想构建一个组件,允许我使用 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>
  );
}

我尝试了什么

  • 我已经按照 this 答案的建议使用了 ? 运算符。
  • 我还使用了此 post 中提到的一些建议,使用 if 语句来验证 theme 不是未定义的。

解决方法

尝试做theme?.Button?.sizes?[size]?.fontSize。您已将按钮和标题函数的主题参数注释为 Partial<FullTheme> 类型。 Partial<> 用于指示每个成员可能未定义。如果前面的变量在运行时未定义,则使用 optional chaining operator 将表达式短路为未定义。

如果你知道运行时在theme?.Button?.sizes[size]?.fontSize中成员访问的整个路径,那么你可以用感叹号代替问号。感叹号是 TypeScript 的 non-null assertion type-operator。这是一个编译时概念。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?