我是第一次在项目中实现打字稿,但是从onPress
传来一个错误,该错误调用toggleModal
。 错误来自onPress
根据React Native docs,DatePickerAndroid.open()执行以下操作:
返回一个Promise,该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>
答案 0 :(得分:1)
您的TouchableOpacity's
onPress有两个问题
1。 toggleModal调用中不兼容的参数: TouchableOpacity
释放了以onPress
作为参数的event
回调,并且您试图在没有显式绑定的情况下调用toggleModal
系统将尝试将onPress's
回调函数给定的参数传递给toggleModal
,这与toggleModal
期望的参数类型为Props
且参数类型为{{ 1}},
这应该通过显式绑定的调用来解决:event
2。从onPress={() => toggleModal(props)}
回调中取消的函数的返回类型,该函数的返回类型期望为onPress's
,而您的返回类型为void
,因为该函数是异步的。
您可以通过将toggleModal声明为普通函数,并使用基于Promise的代码来等待呼叫来解决此问题。
出现 year 问题,原因是不能保证年份的值始终是数字,因此在here中也有可能未定义年份
希望这会有所帮助。谢谢。干杯!