我是第一次在项目中实现打字稿,但是从onPress
传来一个错误,它调用了toggleModal
。 错误来自onPress
根据React Native docs,DatePickerAndroid.open()执行以下操作:
返回一个Promise,它将被一个包含动作的对象调用,年,月(0-11),天(如果用户选择了日期)。如果用户取消对话框后,Promise仍将通过操作解决是DatePickerAndroid.dismissedAction,所有其他键是未定义。
有人可以澄清错误是否来自以下方面以及如何解决吗?
onPress: Function
键入onPress作为函数?错误
src/DatePicker.tsx:109:25 - error TS2769: No overload matches this call.
Overload 1 of 2, '(props: Readonly<TouchableOpacityProps>): TouchableOpacity', gave the following error.
Type '(props: Props) => Promise<void>' is not assignable to type '(event: GestureResponderEvent) => void'.
Types of parameters 'props' and 'event' are incompatible.
Type 'GestureResponderEvent' is missing the following properties from type 'Props': title, onPress, onValueChange, mode
Overload 2 of 2, '(props: TouchableOpacityProps, context?: any): TouchableOpacity', gave the following error.
Type '(props: Props) => Promise<void>' is not assignable to type '(event: GestureResponderEvent) => void'.
109 <TouchableOpacity onPress={toggleModal} style={styles.fieldTextContainer}>
类型
// TypeScript: Types
interface Props {
title: string,
onPress: Function,
onValueChange: Function,
mode: 'calendar' | 'spinner' | 'default',
minDate?: Date | number;
maxDate?: Date | number;
}
interface AndroidProps {
action: 'dateSetAction' | 'dismissedAction',
newDate?: Date;
year?: number;
month?: number;
day?: number;
}
toggleModal
// Toggle Modal
const toggleModal = async (props: Props) => {
try {
// Check Platform (iOS)
if (Platform.OS === 'ios') {
// React Hook: Toggle Modal
toggle((modalVisible) => !modalVisible);
}
// Check Platform (Android)
if (Platform.OS === 'android') {
const { action, year, month, day } : AndroidProps = await DatePickerAndroid.open({
date: date,
mode: props.mode,
});
// Action: Date Set
if (
action === DatePickerAndroid.dateSetAction
&& year !== undefined
&& month !== undefined
&& day !== undefined
) {
// New Date
let newDate:Date = new Date(year, month, day);
// Select Date
selectDate(newDate);
}
// Action: Dismissed
if (action === DatePickerAndroid.dismissedAction) {
// Do Nothing
}
};
}
catch (error) {
console.log(error);
}
};
DatePicker.tsx
<TouchableOpacity onPress={toggleModal} style={styles.fieldTextContainer}>
<Text style={styles.fieldText} numberOfLines={1}>{date ? moment(date).format('MMM Do, YYYY') : 'Select'}</Text>
<Icon name="ios-arrow-forward" size={22} style={styles.arrowForward}/>
</TouchableOpacity>
与您的TouchableOpacity's
onPress有两个问题
1。 toggleModal调用中不兼容的参数: TouchableOpacity
释放以onPress
作为其参数的event
回调,并且您试图在没有显式绑定的情况下调用toggleModal
,即系统将尝试传递给定的参数通过onPress's
回调到toggleModal
是不兼容的,因为toggleModal
期望类型为Props
的参数并且正在获得类型为event
的参数,
这应该通过显式绑定的调用来解决:onPress={() => toggleModal(props)}
2。从onPress's
回调中取消的函数的返回类型,期望该函数的返回类型为void
,而您的函数的返回类型为Promise
,因为该函数是异步的。您可以通过将您的toggleModal声明为普通函数,并使用基于Promise的代码来等待呼叫来解决此问题。
涉及year问题,由于不能确保年份值始终是数字,因此在here中也有未定义的年份。
希望这会有所帮助。谢谢。干杯!