Создание пользовательских компонентов в React Native с помощью TypeScript - PullRequest
0 голосов
/ 28 апреля 2018

Я решил преобразовать свой проект 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>
    );
  }
}

Я получаю красное подчеркивание ... this.getProps () в компоненте MyButton. Также this.props.title и this.props.onPress не идентифицируются.

Не могли бы вы помочь мне с типами, которые мне нужно определить для этих двух классов.

Спасибо

1 Ответ

0 голосов
/ 29 апреля 2018

Во-первых, вы должны объявить, что 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>
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...