【问题标题】:Typescript in React NativeReact Native 中的打字稿
【发布时间】:2021-09-22 02:30:43
【问题描述】:

我的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 和界面状态。

然后在 mu export default class App 里面我把&lt;Props, State&gt; 放在最后。

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

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

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

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

抱歉,我是 react native 和 typescript 的新手,所以我正在尝试尽可能多地学习仅使用类组件。

【问题讨论】:

    标签: javascript reactjs typescript react-native


    【解决方案1】:
    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    相关资源
    最近更新 更多