ReactNative中组件函数传参

81 阅读1分钟
<Button  
style={modalStyles.footerBtn}  
title="Cancel"  
onPress={onClose}  
size={'small'}  
appearance={'outline'}>  
取消  
</Button>

在 React Native 中,onPress 属性期望一个函数作为值。当你写 onPress={onLogin(username, password)} 时,onLogin(username, password) 会立即执行这个函数,并将其返回值(通常是 undefined)作为 onPress 的值。这就是为什么会报错,因为 onPress 需要一个函数,而不是函数的返回值。

如果你想在按钮被点击时传递参数给 onLogin,你可以使用一个箭头函数,如下所示:

javascript<Button 
  style={modalStyles.footerBtn} 
  title="Login" 
  onPress={() => onLogin(username, password)} 
  size={'small'} 
  appearance={'outline'}>
  确认
</Button>

在这个例子中,onPress 被设置为一个箭头函数,这样当按钮被点击时,onLogin 函数才会被调用,并且会传递 username 和 password 作为参数。