React Native + Typescript结合MobX如何定义接口及属性类型
完整修改实现代码
import { observable, computed, action } from "mobx"; import { observer } from "mobx-react-lite"; import { View, Text, StyleSheet } from "react-native"; import { Button } from "react-native-paper"; class TodoStore { @observable // 需求2:添加items内联类型定义 public items: Array<{ title: string; checked: boolean }> = [{ title: "hire great RN dev", checked: false }]; @computed public get itemCount(): number { return this.items.length; } @action public addItem = (title: string) => { this.items.push({ title, checked: false }); }; @action // 补全index参数类型,避免隐式any报错 private toggleItemCheck = (index: number) => { this.items[index].checked = !this.items[index].checked; }; } const todoStore = new TodoStore(); // 需求1:定义TodoScreen的Props接口 interface TodoScreenProps { titleStringFromParent: string; } // 修正组件名首字母大写,符合React规范,绑定Props类型 export const TodoScreen: React.FC<TodoScreenProps> = observer((props) => { const { titleStringFromParent } = props; return ( <View> {/* 修复React Native不支持h1标签的问题,替换为Text组件,可通过style调整字号粗细 */} <Text style={styles.title}>{titleStringFromParent}</Text> {todoStore.items.map((item, index) => ( // 给遍历元素加唯一key,修复React警告,绑定点击事件传当前index <View key={index} style={styles.itemRow}> <Text>{item.title}</Text> <Button onPress={() => todoStore.toggleItemCheck(index)}> {item.checked ? "取消勾选" : "勾选"} </Button> </View> ))} </View> ); }); // 补充基础样式,可根据需求调整 const styles = StyleSheet.create({ title: { fontSize: 24, fontWeight: 'bold', marginVertical: 16, marginHorizontal: 12 }, itemRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 12, marginVertical: 8 } });
主要修改点说明
- 为
TodoStore的items属性添加了内联类型约束,限定数组元素必须包含string类型的title和boolean类型的checked字段 - 新增
TodoScreenProps接口,约束组件入参必须包含string类型的titleStringFromParent属性 - 修复了
toggleItemCheck方法参数index隐式any的问题,添加了number类型声明 - 修正了React Native中使用h1标签的错误,替换为原生Text组件并补充基础样式
- 修复了列表遍历没有添加key属性、
toggleItemCheck调用没有传入索引参数的运行bug - 修正组件名首字母为大写,符合React组件命名规范
内容的提问来源于stack exchange,提问作者Shuib Abdillahi
相关产品推荐
相关产品推荐

