如何将函数传递给反应本机自定义组件但不传递 运行 直到 onPress

How to pass a function to a react native custom component but not run until onPress

我是 RN 的新手。编写我的第一个应用程序。我阅读了有关传递函数的文档,但不清楚如何解决我的问题。我已经为自己构建了一个自定义按钮组件。

import React from 'react'
import { View, TouchableOpacity, Text } from 'react-native'
import { Theme } from '../Styles/Theme';
import { AntDesign } from '@expo/vector-icons'


export const CButton = ({text, icon = null, iconSide = null, onPress}) => {
return (
    <TouchableOpacity onPress={onPress} >
        <View style={Theme.primaryButton}>
            {iconSide == "left" && icon &&
                <AntDesign style={Theme.primaryButtonIcon} name={icon} size={24} color="white" />
            }
            <Text style={Theme.primaryButtonText}>{text}</Text>

            {iconSide == "right" && icon &&
                <AntDesign style={Theme.primaryButtonIcon} name={icon} size={24} color="white" />
            }
        </View>
    </TouchableOpacity>
)
}

我认为这是非常基本的东西。

在这种情况下,我将按钮用作登录按钮:

 <CButton
                text="Login"
                icon="right"
                iconSide="right"
                onPress={login(email, password)}
            />

我将登录名(电子邮件、密码)传递给 onPress 道具,然后在我的自定义组件中使用它,例如:

<TouchableOpacity onPress={() => onPress} >

问题是我这样做是在加载时调用函数(我知道这是一个网络术语)。还没等我按下按钮。

如何确保 onPress 仅在按下按钮时发生?

TIA

你的方式是在组件渲染的时候直接调用登录函数

你只需要像这样修改你对组件的使用

<CButton
     text="Login"
     icon="right"
     iconSide="right"
     onPress={()=> login(email, password)}
/>