You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native+Typescript类组件无Props时能否省略Props接口定义?

问题解答

核心结论

不行,你不能直接将泛型参数改成<State>,React.Component的泛型参数顺序是固定的:第一个参数是组件接收的Props类型,第二个参数才是组件内部的State类型,位置不能调换。如果你直接写React.Component<State>,相当于把你定义的State接口当成了Props的类型,和你的需求完全不符。

不需要接收外部Props的正确写法

你可以按照下面的步骤修改代码即可:

  1. 删除你自定义的Props接口,它确实没有存在的必要
  2. 给React.Component的第一个泛型参数传入空对象类型{},表示该组件不需要接收任何外部props
  3. 对应的constructor中的props类型同步修改为{},如果你constructor内部完全没有用到props,甚至可以省略props参数,直接调用无参的super()

修改后的核心代码示例:

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

// 只保留State接口即可
interface State {
  totalCount: number;
  readingCount: number;
  doneCount: number;
}

// 第一个泛型传{}表示无外部Props,第二个传State
export default class App extends React.Component<{}, State> {
  // 不需要处理props的话constructor可以简化成这样
  constructor() {
    super();
    this.state = {
      totalCount: 0,
      readingCount: 0,
      doneCount: 0,
    };
  }

  // 原有render和styles代码不需要做任何修改
  render() {
    // ... 原有代码
  }
}

const styles = StyleSheet.create({
  // ... 原有样式代码
})

补充说明

如果后续你需要给该组件传入子元素(children),可以将Props类型替换为React.PropsWithChildren<{}>,这样TypeScript就不会对传入的children报类型错误,当前不需要的话用{}就完全满足要求。


内容的提问来源于stack exchange,提问作者user16869183

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:06:04