首页 > 解决方案 > 带条件的 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>

期望使用条件调用函数。感谢有人可以向我介绍这一点。之前谢谢。

标签: react-native

解决方案


你不是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')}

推荐阅读