首页 > 解决方案 > React Native & Typescript,如何使用 MobX 添加界面

问题描述

我正在尝试为 todoScreen 的道具添加一个界面,但我是 Typescript 和 RN 的新手,所以有人可以在这里帮助我吗?我确定代码中也存在一些错误。

我还需要在商店中为“项目”添加一个内联类型

import { observable, computed, action } from "mobx";
import { observer } from "mobx-react-lite";
import { View, Text } from "react-native";
import { Button } from "react-native-paper";

class TodoStore {
  @observable
  public items = [{ title: "hire great RN dev", checked: false }];


  @computed
  public get itemCount(): number {
    return this.items.length;
  }

  @action
  public addItem = (title: string) => {
    this.items.push({ title, checked: false });
  };

  @action
  private toggleItemCheck = (index) => {
    this.items[index].checked = !this.items[index].checked;
  };
}

const todoStore = new TodoStore();

export const todoScreen: React.FC = observer((props) => {
  const { titleStringFromParent } = props;

  return (
    <View>
      <h1>{titleStringFromParent}</h1>
      {todoStore.items.map((item) => (
        <>
          <Text>{item.title}</Text>
          <Button onPress={todoStore.toggleItemCheck}>
            {item.checked ? "uncheck" : "check"}
          </Button>
        </>
      ))}
    </View>
  );
});

标签: typescriptreact-nativemobx

解决方案


我很确定如果您有默认项目,那么类型将被自动推断。但是,如果您仍想手动添加类型,则只需将其键入为带有对象的常规数组,如下所示:

interface Item {
  title: string;
  checked: boolean;
}

class TodoStore {
  @observable
  public items: Array<Item> = [{ title: "hire great RN dev", checked: false }];

  // ...
}

推荐阅读