react-native - 带条件的 Onpress 不会调用函数
问题描述
我对按钮功能有一些问题onPress
,如果我创建按钮并直接调用函数,它工作得很好,但如果我使用条件它不会调用该函数。
我已经在下面创建了2个按钮来模拟,标题为“提交正常”的按钮可以调用函数并成功传递属性,标题为“提交条件”的按钮不会调用this.makeRemoteRequest.bind(this);
,但如果你发出警报它会正常反应,如果调用没有任何反应功能。
<Input
containerStyle={{ width: '90%' }}
placeholder="Predefined User ID"
label="User ID"
labelStyle={{ marginTop: 16 }}
editable={false}
value={this.state.userid}
onChangeText={input_user_id => this.setState({ input_user_id })}
/>
<Input
containerStyle={{ width: '90%' }}
placeholder="Please fill services request notes here"
label="Reason"
labelStyle={{ marginTop: 16 }}
onChangeText={input_services_detail => this.setState({ input_services_detail })}
/>
<Button
title='Submit Conditional'
onPress={() => {
if (this.state.input_services_detail != null)
{
this.makeRemoteRequest.bind(this);
}
else
{
Alert.alert('Please fill the service detail first');
}
}}><Text style={styles.buttonText}>Submit Aset</Text>
</Button>
<Button
title='Submit Normal'
onPress={this.makeRemoteRequest.bind(this)}><Text style={styles.buttonText}>Submit Aset</Text>
</Button>
</View>
期望使用条件调用函数。感谢有人可以向我介绍这一点。之前谢谢。
解决方案
你不是this.makeRemoteRequest
在调用你的条件,你只是在绑定它。像这样更改您的条件onPress
道具:
onPress={this.state.input_services_detail != null ? this.makeRemoteRequest.bind(this) : () => Alert.alert('Please fill the service detail first')}
而且您不需要!= null
:
onPress={this.state.input_services_detail ? this.makeRemoteRequest.bind(this) : () => Alert.alert('Please fill the service detail first')}
推荐阅读
- hadoop - AWS EMR 未生成 NameNode FsImage
- javascript - 循环遍历数组并将变量与数组进行比较
- python - 如何在位于不同路径的包上使用 mod 选项“-m”运行 Python3?
- python - Django 信号即使对于 django 也能正常工作 - 为模型编写时是管理员
- python - 熊猫重命名后熊猫concat没有提供任何条目
- drupal - drupal webform 确认消息匿名用户
- reactjs - 运行两个不以 package.json 结尾的脚本
- ssl - 在 tomcat 8 中启用 SSL
- python - 从谷歌存储桶下载文件
- php - php artisan migrate 没有做任何事情