首页 > 解决方案 > 如何在 React Native 中调用 Alert onPress 并传递一些参数

问题描述

在这里,我在文本字段上调用警报功能 onPress 。在调用该函数时,我试图打开警报并确认我正在调用另一个函数。但是如果我调用 "showAlert1()" 就会挂起。这个函数被多次调用,我必须调用 showAlert() 函数 onPress 并且我必须在其中发送一些值。并在警报框上的确认 OK 按钮上,我必须上传到服务器。

showAlert1(code, name, version) {
  console.log("data alaert abc", code, name, version);
  Alert.alert(
    'Confirmation',
    'Are you sure you want to migrate this tariff',
    [
      {
        text: 'Cancel',
        onPress: () => console.log('Cancel Pressed'),
        style: 'Cancel',
      },
      { text: 'Proceed', onPress: () => this.confirmTariffMigration(code, name, version) },
    ]
  );
}

confirmTariffMigration = (code, name, version) => {
  console.log("hhhhdhhdhdhdhhdd", code, name, version);
  const objData = {
    addofferingActionCode: '',
    offeringCode: '',
    offeringName: ''
  }
  this.props.updateTariffMigration(objData)
}
<View style={{ marginLeft: 5, marginRight: 5, marginTop: 10, backgroundColor: '#f1f1f1' }}>
  {
    tariffMigrationData.map((data, index) => {
      return (
        //  <TouchableOpacity key={index} onPress={this.showAlert1(data)}>
        <View style={{ marginBottom: 10, marginLeft: 5, marginRight: 5 }} key={index}>
          <Card>
            <CardItem header style={{ backgroundColor: '#fff', width: '100%', justifyContent: 'space-between', borderBottomColor: '#f1f1f1', borderBottomWidth: 1 }}>
              <View style={{ flexDirection: 'column', justifyContent: 'space-between' }}>
                <View>
                  <RegularText text={`${data.offering.name}`} style={{ fontWeight: 'bold' }} />
                  <SmallText text={` ID ${data.offering.code}`} textColor="grey" />
                </View>
              </View>
              <View style={{
                backgroundColor: 'blue',
                borderRadius: 75, height: 25, paddingRight: 10, paddingLeft: 10, paddingTop: 5
              }}>
                <SmallText text={'Proceed'} onPress={this.showAlert1(data.offering.code, data.offering.version, data.offering.name)} textColor='white' />
              </View>
            </CardItem>
          </Card>
        </View>
      )
    }
  }
</View>

标签: javascriptreactjsreact-nativeecmascript-6alert

解决方案


尝试改变:

<TouchableOpacity key={index} onPress={this.showAlert1(data)}>

<TouchableOpacity key={index} onPress={() => this.showAlert1(data)}>

showAlert1 (code,name,version) {  
    // code
}

showAlert1 = (code,name,version) => {  
    // code
}

推荐阅读