我正在将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>
);
}
}
请帮助。
答案 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()
中分配了一个值
希望这会有所帮助!