Typescript useState 错误布尔值没有调用签名

Typescript useState error boolean has no call signatures

我在使用 Typescript 和 React Native 时遇到控制台错误的问题。它说“此表达式不可调用。类型 'Boolean' 没有调用签名。” 代码很简单,主页上只有两张卡片,如果用户单击其中一张,它应该将用户转到该页面。为了更好地理解钩子,我试图通过 useState 来实现。这是 home.tsx:

中的代码
import { Button, StyleSheet, Text, View } from "react-native"

import CardsComponent from "../../components/cards/cards"
import EcoNoticias from "../../components/EcoNoticias/EcoNoticias";
import React from "react";
import { useState } from "react";

export interface HomeComponentProps {
    
}
 
const HomeComponent: React.FC<HomeComponentProps> = () => {
    const [buttonPressed, setButtonPressed] = useState<boolean>(false);

    const handlePage = () => {
        setButtonPressed(true);
    };
    
    return (
        <>
            <View>
                <Text style={styles.title}>Hello User</Text>
                <View>
                    {() => buttonPressed(false)} ?
                    <CardsComponent>
                        <Text style={styles.textCard}>Tips</Text>
                        <Button title='Tips' onPress={() => {}} />
                    </CardsComponent>
                    <CardsComponent>
                        <Text style={styles.textCard}>Eco-Noticias</Text>
                        <Button title='Eco-Noticias' onPress={handlePage} />
                    </CardsComponent> : <EcoNoticias />
                </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;

错误在 if ternario,第 24 行:“buttonPressed(false)”。

{() => buttonPressed(false)} ?

这一行表示要切换回普通 javascript(与 jsx 相对),然后使用文本 () => buttonPressed(false) 创建一个函数,然后切换回 jsx 并放入字符串“?”屏幕上。您得到的打字稿错误指出,由于 buttonPressed 是一个布尔值,因此尝试将其作为函数调用是没有意义的。

从评论来看,您的意图似乎是这样的:

{buttonPressed === false ? (
  <React.Fragment>
    <CardsComponent>
      <Text style={styles.textCard}>Tips</Text>
      <Button title="Tips" onPress={() => {}} />
    </CardsComponent>
    <CardsComponent>
      <Text style={styles.textCard}>Eco-Noticias</Text>
      <Button title="Eco-Noticias" onPress={handlePage} />
    </CardsComponent>
  </React.Fragment>
) : (
  <EcoNoticias />
)}

<React.Fragment>是必须的,因为你要有多个元素。如果您愿意,可以使用 shorthand <></> 而不是 <React.Fragment></React.Fragment>