在react-native-accordion的renderheader函数内调用TouchableOpacity的onPress上的函数

时间:2018-02-19 06:27:10

标签: react-native ecmascript-6

我想在 TouchableOpacity 的onPress上调用deleteInvoice函数,但是 它正在显示

  

错误:undefined不是函数(评估this3.deleteInvoice())

如何调用此功能?

   import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  ScrollView, ListView, TouchableOpacity, TouchableNativeFeedback, TouchableWithoutFeedback, Alert
} from 'react-native';
import { Icon, FormInput, Button, } from 'react-native-elements';
import * as Animatable from 'react-native-animatable';
import Collapsible from 'react-native-collapsible';
import Accordion from 'react-native-collapsible/Accordion';
import { Actions } from 'react-native-router-flux';


let SQLite = require('react-native-sqlite-storage');

let db = SQLite.openDatabase({ name: 'TEST.db', createFromLocation: "~TEST.db", location: 'Library' }, this.openCB, this.errorCB, this.successCB);

var myInvNo = [], totalAmount = [], cmpn = [], header = [1, 2, 3, 4, 5], content = [], a, downloadedInvoiceList = []


export default class ExampleView extends Component {
  constructor(props) {
    super(props);
    this.fetchFromServer = this.fetchFromServer.bind(this)
    this.downloadInvoiceListFromServer = this.downloadInvoiceListFromServer.bind(this)
    this.populateInvoiceList = this.populateInvoiceList.bind(this)
    this._deleteInvoice = this._deleteInvoice.bind(this)

  }
  state = {
    activeSection: false,
    collapsed: true,
    invoiceno: '',
    custname: [],
    invoicedate: [],
    invoicejson: [],
    company: '',
    searchInvoice: '',
    down: false

  };

  componentDidMount() {

    this.populateInvoiceList();

  }



  populateInvoiceList() {

    db.transaction((tx) => {
      // tx.executeSql('INSERT INTO TDOCHEADER (INVNO,INVID,INVDAE,DOCTYPE,CUSTNM,ISPROSS,INVJSON,TALLYVOUCHERID,PROCESSDT,PROCESSTM,REASON,STATUS)
      // VALUES(?,?) ', ['VISHAL',7387259868], (tx, results) => {
      //   console.log("Record Inserted");
      // });

      tx.executeSql('SELECT * FROM TDOCHEADER WHERE  DOCTYPE=? ', ['INVOICE'], (tx, results) => {
        console.log("Query completed");

        // Get rows with Web SQL Database spec compliance.

        var len = results.rows.length;
        var arr = [];
        console.log(`Length :${len}`)
        for (let i = 0; i < len; i++) {
          let row = results.rows.item(i);

          console.log(`record :${results.rows.item(i).INVJSON}`)

          var s = JSON.parse(results.rows.item(i).INVJSON)
          jsonObj = JSON.parse(results.rows.item(i).INVJSON)


          myInvNo.push({
            'header': results.rows.item(i).INVNO + '(' + s.TAX.TOTAL + ') - ' + s.UpdateVariables[0].H_cmpn + '\n' + s.UpdateVariables[0].H_custnm,
            'data': 'Invoice Date:' + s.UpdateVariables[0].H_invdt + '\nDue Date:' + s.UpdateVariables[0].H_duedt
              + '\nTotal Amount:' + s.TAX.TOTAL + '\nCompany:' + s.UpdateVariables[0].H_cmpn
              + '\nRemarks:' + s.UpdateVariables[0].D_dremark + '\n' + ((results.rows.item(i).REASON != null) ? 'Reason:' + results.rows.item(i).REASON : ''),
            'InvNo': results.rows.item(i).INVNO
          })


          content.push(s.UpdateVariables[0].H_invdt)
          console.log(`content :${content}`)
          a = [
            {
              'header': myInvNo,
              'data': content
            }
          ]
          console.log(`a :${a}`)
          this.setState({

            invoiceno: row.INVNO,
            custname: row.CUSTNM,
            invoicedate: row.INVDAE,
            invoicejson: row.INVJSON,
            company: s.UpdateVariables[0].H_cmpn
          });
          arr.push(this.state.invoiceno)
          console.log(`arr :${arr.toString()}`)
        }
      });
    });
  }

  errorCB(err) {
    console.log("SQL Error: " + err);
  }

  successCB() {
    console.log("SQL executed fine");
  }

  openCB() {
    console.log("Database OPENED");
  }



  downloadInvoiceListFromServer() {
    this.fetchFromServer();
    this.populateInvoiceList();
  }

  fetchFromServer() {
    fetch('http://itransformsolutions.co.in/zkTallyAndroidTest/AppServlet', {
      method: 'POST',
      headers: {
        'Access-Control-Allow-Origin': 'http://itransformsolutions.co.in',
        Origin: 'http://itransformsolutions.co.in',
        'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
        'Access-Control-Allow-Headers': 'X-PINGOTHER',
        Pragma: 'no-cache',
        'Cache-Control': 'no-cache',
        'access-control-allow-credentials': "true",
        Accept: 'application/json;application / xhtml + xml, application / xml; q = 0.9, image / webp, * / *',
        'Content-Type': 'application/json;charset=UTF-8;x-www-form-urlencoded',
        'Agent-the-User': 'the Mozilla / 5.0 (the Windows NT 6.1; the WOW64) AppleWebKit / 537.36 (KHTML, like the Gecko) the Chrome / 44.0.2403.89 Safari / 537.36',
        server: "cloudflare-nginx",
        'the-Host': 'http://itransformsolutions.co.in'
      },
      body: JSON.stringify({


        "data": {
          Client: "9035",
          DOCTYPE: "INVOICE"
        },
        "Transaction": { Transaction: "PullERRORINV" }

      })
    })
      .then((response) => response.json())
      .then((response) => {

        let x = response
        console.log(`ressssssssssssss:${JSON.stringify({ response })}`);
        for (let i = 0; i < response.INVOICEDATA.INVOICE_List.length; i++) {
          console.log(`clnt:${response.INVOICEDATA.INVOICE_List[i].CLNT}`);
          console.log(`doctype:${response.INVOICEDATA.INVOICE_List[i].DOCTYP}`);
          console.log(`docid:${response.INVOICEDATA.INVOICE_List[i].DOCID}`);
          console.log(`reason:${response.INVOICEDATA.INVOICE_List[i].REASON}`);
          console.log(`status:${response.INVOICEDATA.INVOICE_List[i].STATUS}`);
          console.log(`invno:${response.INVOICEDATA.INVOICE_List[i].ORDERJSON.UpdateVariables[0].H_invno}`);
          console.log(`invdate:${response.INVOICEDATA.INVOICE_List[i].ORDERJSON.UpdateVariables[0].H_invdt}`);
          console.log(`custnm:${response.INVOICEDATA.INVOICE_List[i].ORDERJSON.UpdateVariables[0].H_custnm}`);
          console.log(`invjson:${response.INVOICEDATA.INVOICE_List[i].ORDERJSON}`);
          let invjson = JSON.stringify(response.INVOICEDATA.INVOICE_List[i].ORDERJSON)
          console.log(`asasasasassa:${JSON.stringify(invjson)}`);
          let doctype = response.INVOICEDATA.INVOICE_List[i].DOCTYP
          let docid = response.INVOICEDATA.INVOICE_List[i].DOCID
          let reason = response.INVOICEDATA.INVOICE_List[i].REASON
          let status = response.INVOICEDATA.INVOICE_List[i].STATUS
          let invno = response.INVOICEDATA.INVOICE_List[i].ORDERJSON.UpdateVariables[0].H_invno
          let invdate = response.INVOICEDATA.INVOICE_List[i].ORDERJSON.UpdateVariables[0].H_invdt
          let custnm = response.INVOICEDATA.INVOICE_List[i].ORDERJSON.UpdateVariables[0].H_custnm
          //    let invjson=response.INVOICEDATA.INVOICE_List[i].ORDERJSON


          downloadedInvoiceList.push(
            "INSERT INTO TDOCHEADER (INVNO,INVID,INVDAE,DOCTYPE,CUSTNM,INVJSON,REASON,STATUS) VALUES('" + invno + "','" + docid + "','" + invdate + "','" + doctype + "','" + custnm + "','" + JSON.stringify(response.INVOICEDATA.INVOICE_List[i].ORDERJSON) + "','" + reason + "','" + status + "')")
        }

        db.transaction((tx) => {
          tx.executeSql('DELETE FROM TDOCHEADER WHERE  STATUS=?', ['ERROR'], (tx, results) => {
            console.log("Invoice Record Deleted having status=Error");
          })
        });

        // console.log(`insert stat111111111:${downloadedInvoiceList[0]}`);  
        for (let i = 0; i < downloadedInvoiceList.length; i++) {
          db.transaction((tx) => {
            tx.executeSql(downloadedInvoiceList[i])
            console.log(`Record Inserted${i}`);
          });
          console.log("Record Inserted ENDDDD");
          //  console.log(`insert stat:${downloadedInvoiceList[i]}`);  
        }

        // Get rows with Web SQL Database spec compliance.


      })
      .catch((error) => {
        console.error(error)
      })
    //   this.populateInvoiceList();
  }


  _deleteInvoice(section)  {
    db.transaction((tx) => {
      tx.executeSql('DELETE FROM TDOCHEADER WHERE  INVNO=?', [section.InvNo], (tx, results) => {
        console.log("Invoice Record Deleted after selection");
      })
    });

    this.populateInvoiceList()
  }

  _toggleExpanded = () => {
    this.setState({ collapsed: !this.state.collapsed });
  }

  _setSection(section) {
    this.setState({ activeSection: section });
  }

  _renderHeader(section, i, isActive, down) {
    return (
      <View >
        <Animatable.View duration={400} style={[styles.header, isActive ? styles.active : styles.inactive]} transition="backgroundColor">
          <View style={{ flexDirection: 'row' }}>
            <View>
              <Icon name='keyboard-arrow-up' size={25} color={isActive ? '#214263' : '#16a085'} />
              <Icon name='keyboard-arrow-down' size={25} color={isActive ? '#1abc9c' : '#214263'} />
            </View>
            <Text style={styles.headerText} > {section.header}</Text>


            <TouchableOpacity onPress={() => Actions.addInvoice({ text: section.InvNo })}>
              <Icon name='edit' size={25} color='skyblue' />
            </TouchableOpacity>

            <Icon name='file-upload' size={25} color='red' />

            <TouchableOpacity onPress={this._deleteInvoice(section)}>
              <Icon name='delete' size={25} color='red' />
            </TouchableOpacity>
          </View>
        </Animatable.View>

      </View>
    );
  }




  _renderContent(section, i, isActive) {
    return (
      <Animatable.View duration={400} style={{ paddingLeft: 45, paddingVertical: 5 }} transition="backgroundColor">
        <Animatable.Text animation={isActive ? 'bounceIn' : undefined}>{section.data}</Animatable.Text>
      </Animatable.View>
    );
  }


  addInvoice=()=> {
    Actions.addInvoice()
  }
  render() {


    return (

      <ScrollView>

        <View style={styles.container}>

          <View style={{ flexDirection: 'row', }}>
            <Icon name='search' size={20} iconStyle={{ paddingLeft: 10, paddingTop: 10 }}
              color='#214263' />
            <FormInput
              placeholder="Inv No"
              onChangeText={(text) => this.setState({ searchInvoice: text })} />
          </View>
          <View style={{ flexDirection: 'row', }}>

            <Accordion
              activeSection={this.state.activeSection}
              sections={myInvNo}
              //  renderHeader={()=>(<Text >{this.state.invoiceno}</Text>)}
              renderHeader={this._renderHeader}
              renderContent={this._renderContent}

              duration={100}
              onChange={this._setSection.bind(this)}
            />

          </View>

          <View style={{ flexDirection: 'row', justifyContent: 'space-between', }}>

            <TouchableOpacity onPress={this.downloadInvoiceListFromServer}>
              <Icon name='file-download' size={40} color='white' containerStyle={{ backgroundColor: '#16a085', borderRadius: 30 }} iconStyle={{ padding: 10 }} />
            </TouchableOpacity>

            <TouchableOpacity onPress={this.addInvoice}>
              <Icon name='add' size={40} color='#4cd137' />
            </TouchableOpacity>

            <TouchableOpacity >
              <Icon name='file-upload' size={40} color='white' containerStyle={{ backgroundColor: '#16a085', borderRadius: 30 }} iconStyle={{ padding: 10 }} />
            </TouchableOpacity>
          </View>

        </View>

      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#F5FCFF',
  },
  title: {
    textAlign: 'center',
    fontSize: 22,
    fontWeight: '300',
    marginBottom: 20,
  },
  header: {
    backgroundColor: '#F5FCFF',
    padding: 10,

  },
  headerText: {
    // textAlign: 'center',
    fontSize: 16,
    fontWeight: '500',
    color: 'white',
    width: 200,
    paddingLeft: 10
  },
  content: {
    padding: 20,
    backgroundColor: '#fff',

  },
  active: {
    backgroundColor: '#1abc9c',
  },
  inactive: {
    backgroundColor: '#16a085',
  },
  selectors: {
    marginBottom: 10,
    flexDirection: 'row',
    justifyContent: 'center',
  },
  selector: {
    backgroundColor: '#F5FCFF',
    padding: 10,
  },
  activeSelector: {
    fontWeight: 'bold',
  },
  selectTitle: {
    fontSize: 14,
    fontWeight: '500',
    padding: 10,
  },
});

1 个答案:

答案 0 :(得分:0)

试图为你的问题提供最简单的解释:

class YourCompo extends Component{

delete = () => {
console.log('passed in a arrow function via a variable');
}

insert(){
console.log('passing in a function directly');
}

render(){
return(
<TouchableOpacity onPress{this.delete}>
</TouchableOpacity>

<TouchableOpacity onPress{() => this.insert()}>
</TouchableOpacity>
);
}

使用 OnPress 的两种方法。 将您的代码与其中一个匹配,您的错误将得到解决。请注意两种语法。 希望有所帮助