Typescript+React Native useState布尔值无调用签名报错如何解决
错误原因
buttonPressed是你声明的布尔类型状态值,本身不是可调用的函数,buttonPressed(false)属于语法错误,直接触发TypeScript的类型校验报错- JSX内的三元表达式语法不规范:仅包裹了判断条件部分,还多写了无意义的箭头函数,整个条件渲染逻辑都需要放在同一对大括号内
修复方案
你当前的布尔状态只能控制展示「卡片列表」和「EcoNoticias页面」,无法区分两张卡片的跳转需求,建议调整状态类型存储页面标识,完整修复后的代码如下:
import { Button, StyleSheet, Text, View } from "react-native" import CardsComponent from "../../components/cards/cards" import EcoNoticias from "../../components/EcoNoticias/EcoNoticias"; // 这里可以导入你要跳转的Tips页面组件 // import Tips from '../../components/Tips/Tips'; import React from "react"; import { useState } from "react"; export interface HomeComponentProps { } // 定义状态可选值类型 type PageType = 'home' | 'tips' | 'eco-noticias' const HomeComponent: React.FC<HomeComponentProps> = () => { const [currentPage, setCurrentPage] = useState<PageType>('home'); // 抽离通用跳转方法 const navigateTo = (page: PageType) => { setCurrentPage(page); }; return ( <> <View> <Text style={styles.title}>Hello User</Text> <View> {currentPage === 'home' ? ( /* 多张卡片需要包在同一个根容器内,这里用React.Fragment简写 */ <> <CardsComponent> <Text style={styles.textCard}>Tips</Text> <Button title='Tips' onPress={() => navigateTo('tips')} /> </CardsComponent> <CardsComponent> <Text style={styles.textCard}>Eco-Noticias</Text> <Button title='Eco-Noticias' onPress={() => navigateTo('eco-noticias')} /> </CardsComponent> </> ) : currentPage === 'eco-noticias' ? ( <EcoNoticias /> ) : ( /* 这里放你的Tips页面组件 */ <Text>Tips页面</Text> )} </View> </View> </> ); }; const styles = StyleSheet.create({ title: { fontSize: 23, paddingBottom: 50, textAlign: 'center', }, textCard: { color: 'white', fontWeight: '700', textAlign: 'center', paddingBottom: 10, }, buttonStyle: { width: '50%', }, }); export default HomeComponent;
核心修改点
- 替换原布尔类型的状态,用联合类型存储当前展示的页面标识,支持多页面切换
- 修正了JSX内条件渲染的语法,把整个三元逻辑放在同一对大括号内
- 多并列元素用Fragment包裹,符合JSX语法要求
- 抽离通用跳转方法,减少重复代码
内容的提问来源于stack exchange,提问作者Joaquin Palacios
相关产品推荐
相关产品推荐

