首页 > 解决方案 > React Native 中的打字稿

问题描述

我的App.tsx文件中有以下代码:

import React from 'react';
import { StyleSheet, View, SafeAreaView, Text } from 'react-native';

export interface Props {
  totalCount: number;
  readingCount: number;
  doneCount: number;
}

interface State {
  totalCount: number;
  readingCount: number;
  doneCount: number;
}

export default class App extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props);

    this.state = {
      totalCount: 0,
      readingCount: 0,
      doneCount: 0,
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <SafeAreaView />
        <View style={styles.headerContainer}>
          <Text style={styles.headerTitle}>Book Worm</Text>
        </View>
        <View style={styles.bodyContainer}>
          <Text>Body</Text>
        </View>
        <View style={styles.footerContainer}>
          <View style={styles.menuContent}>
            <Text>Book List</Text>
            <Text>{this.state.totalCount}</Text>
          </View>
          <View style={styles.menuContent}>
            <Text>Reading</Text>
            <Text>{this.state.readingCount}</Text>
          </View>
          <View style={styles.menuContent}>
            <Text>Done</Text>
            <Text>{this.state.doneCount}</Text>
          </View>
        </View>
        <SafeAreaView />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  headerContainer: {
    borderBottomWidth: 1,
    borderColor: 'black',
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
  },
  headerTitle: {
    fontSize: 24,
  },
  bodyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  menuContent: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  footerContainer: {
    flexDirection: 'row',
    borderTopWidth: 1,
    borderColor: 'black',
    height: 50,
  },
});

请注意,在顶部我有导出接口 Props 和接口状态。

然后在我放在<Props, State>最后的 mu 导出默认类 App 中。

我的问题是,因为我只需要状态,并且这个类组件不会收到任何道具,我可以省略export interface Props顶部的并简单地保留接口状态。然后在我的导出默认值应该看起来export default class App extends React.Component<State> {没有“道具”这个词。

我尝试将其删除,但在构造函数中需要它,如下所示:

constructor(props: Props) {
  super(props);

  this.state = {
    totalCount: 0,
    readingCount: 0,
    doneCount: 0,
  };
}

抱歉,我对本机和打字稿做出反应是新手,所以我正在尝试尽可能多地使用类组件来学习。

标签: javascriptreactjstypescriptreact-native

解决方案



推荐阅读