使用TypeScript在React Native中创建自定义组件

时间:2018-04-28 11:11:19

标签: typescript react-native

我决定将我的ReactNative项目转换为TypeScript。我是TypeScript的新手,我发现很难用自定义组件和继承来解决这个问题。这是我的(按比例缩小)代码

import React, { Component } from "react";
import { Button, View } from "react-native";

interface IMyComponentProps extends React.Props<IMyComponentProps> {
  colWidth?: number;
}

class MyComponent extends Component<IMyComponentProps> {
  getProps() {
    return this.props;
  }
}

class MyButton extends MyComponent {
  render() {
    return (
      <View {...this.getProps()}>
        <Button title={this.props.title} onPress={this.props.onPress} />
      </View>
    );
  }
}

我在MyButton组件中的... this.getProps()上有一个红色下划线。此外,还没有确定this.props.title和this.props.onPress。

您能否帮我解决我需要为这两个类定义的类型。

由于

1 个答案:

答案 0 :(得分:1)

首先,您需要声明MyButton具有更多特定道具,因此必须参数化MyComponent

class MyComponent<P extends IMyComponentProps> extends Component<P> {
  getProps() {
    return this.props
  }
}

然后正确地扩展MyComponent并声明其道具:

interface IMyButtonProps extends IMyComponentProps {
  colWidth?: number;
  title: string;
  onPress: () => void;
}


class MyButton extends MyComponent<IMyButtonProps> {
  render() {
    return (
      <View {...this.getProps()}>
        <Button title={this.props.title} onPress={this.props.onPress} />
      </View>
    );
  }
}

然后,除非您使用难以推理的引用,否则不会延长React.Props 。只需声明您的接口:

interface IMyComponentProps {
  colWidth?: number;
}
interface IMyButtonProps extends IMyComponentProps {
  title: string;
  onPress: () => void;
}

现在一起!

mport React, { Component } from "react";
import { Button, View } from "react-native";

interface IMyComponentProps {
  colWidth?: number;
}

class MyComponent<P extends IMyComponentProps> extends Component<P> {
  getProps() {
    return this.props
  }
}

interface IMyButtonProps extends IMyComponentProps {
  title: string;
  onPress: () => void;
}

class MyButton extends MyComponent<IMyButtonProps> {
  render() {
    return (
      <View {...this.getProps()}>
        <Button title={this.props.title} onPress={this.props.onPress} />
      </View>
    );
  }
}