【问题标题】:How to write proper `Keyboard.addListener` in React Native with TypeScript?如何使用 TypeScript 在 React Native 中编写正确的 `Keyboard.addListener`?
【发布时间】:2019-10-17 18:40:14
【问题描述】:

我正在重写一个 TypeScript 教程。

它应该在componentDidMount 之后console.log,但事实并非如此。它也没有显示任何错误。

我做错了什么?

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

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

【问题讨论】:

    标签: android typescript react-native expo


    【解决方案1】:

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

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

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

    ...
    export class Logo extends React.PureComponent {
      constructor(props) {
        super(props);
      }
    
      keyboardDidShowListener!: EmitterSubscription;
      keyboardDidHideListener!: EmitterSubscription;
    ...
    
    

    请注意,我在属性后添加了一个!,以告诉 TypeScript 我确保它获得了分配的值,在这种情况下,在 componentDidMount()

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-11-22
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 2021-05-18
      • 2021-05-05
      相关资源
      最近更新 更多