如何使用TypeScript在React Native中编写正确的`Keyboard.addListener`?

时间:2019-06-01 11:56:06

标签: android typescript react-native expo

我正在将TypeScript重写为教程。

它应该在console.log之后componentDidMount,但不是。它也没有显示任何错误。

我在做什么错了?

这是我的代码(已为您最小化):

import React from 'react';
import { View, Text, Animated, Keyboard } from 'react-native';

export class Logo extends React.PureComponent {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    console.log(`Hey, I am mounted!`);

    this.keyboardDidShowListener = Keyboard.addListener(
      `Keyboard will show`,
      this.keyboardWillShow
    );

    this.keyboardDidHideListener = Keyboard.addListener(
      `Keyboard will hide`,
      this.keyboardWillHide
    );
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  keyboardWillShow = () => {
    console.log(`Keyboard shows`);
  };

  keyboardWillHide = () => {
    console.log(`Keyboard hides`);
  };

  render() {
    return (
      <View>
        <Text>
          Type the amount right here
        </Text>
      </View>
    );
  }
}

请帮助。

此处的教程代码:https://github.com/HandlebarLabs/currency-converter-starter/blob/module-3-lesson-10-animation/app/components/Logo/Logo.js

1 个答案:

答案 0 :(得分:1)

您可以导入EmitterSubscription接口,这是Keyboard.addListener(...)从react-native返回的类型。

看起来像这样: import { Keyboard, EmitterSubscription } from 'react-native';

然后您可以将其添加到您的代码中:

...
export class Logo extends React.PureComponent {
  constructor(props) {
    super(props);
  }

  keyboardDidShowListener!: EmitterSubscription;
  keyboardDidHideListener!: EmitterSubscription;
...

请注意,我在属性之后添加了!,以告知TypeScript确保在componentDidMount()中分配了一个值

希望这会有所帮助!