如何在TypeScript中为Redux dispatch回调类型的onPress属性设置类型?
为Redux dispatch对应的组件onPress属性定义TypeScript类型
问题核心
你传给Item组件的onPress是一个无参数、无返回值的回调函数,而非AppDispatch类型(AppDispatch是Redux dispatch函数本身的类型),直接使用AppDispatch会导致类型不匹配。
正确的类型定义方式
有两种常用方案:
基础简洁方案
TouchableOpacity的onPress默认接受() => void类型的回调,这是最贴合场景的写法:interface ItemProps { item: Custom_date, onPress: () => void, // 替换原有的AppDispatch backgroundColor: StyleProp<ViewStyle>, textColor: StyleProp<TextStyle> }支持事件对象的进阶方案
如果需要在回调中获取点击事件的详细信息,可以使用React Native提供的GestureResponderEvent类型:import { GestureResponderEvent, StyleProp, ViewStyle, TextStyle } from 'react-native'; interface ItemProps { item: Custom_date, onPress: (event: GestureResponderEvent) => void, backgroundColor: StyleProp<ViewStyle>, textColor: StyleProp<TextStyle> }
额外类型优化建议
- 避免用
any定义样式,改用React Native提供的StyleProp<ViewStyle>和StyleProp<TextStyle>,能获得完整的类型提示与语法检查。 - 给
renderItem的参数指定类型,消除隐式any:const renderItem = ({ item }: { item: Custom_date }) => { // 原有逻辑 } - 给
useDispatch显式指定AppDispatch类型,让dispatch触发action时获得类型校验:const dispatch = useDispatch<AppDispatch>()
修改后的完整代码示例
import { AppDispatch } from "../redux/store" import { GestureResponderEvent, StyleProp, ViewStyle, TextStyle, TouchableOpacity, Text, FlatList } from 'react-native'; import { useSelector, useDispatch } from 'react-redux'; interface ItemProps { item: Custom_date, onPress: () => void, backgroundColor: StyleProp<ViewStyle>, textColor: StyleProp<TextStyle> } const Item = ({ item, onPress, backgroundColor, textColor }: ItemProps) => ( <TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}> <Text style={[styles.dateTitle, textColor]}>{item.title}</Text> </TouchableOpacity> ); export const DateHeader = () => { const { date } = useSelector((store: RootState) => store.nutrition) const dispatch = useDispatch<AppDispatch>() const renderItem = ({ item }: { item: Custom_date }) => { const backgroundColor = item.id === date.id ? "#033F40" : "#BDF0CC"; const color = item.id === date.id ? '#BDF0CC' : '#033F40'; return ( <Item item={item} onPress={() => dispatch(setDate(item))} backgroundColor={{ backgroundColor }} textColor={{ color }} /> ); } return ( <FlatList renderItem={renderItem} {...props} /> ) }
内容的提问来源于stack exchange,提问作者benwl
相关产品推荐
相关产品推荐

