简体   繁体   中英

React native passing variable inside a function

I have a function and I want to pass a variable inside that function. This sendDraft function will receive parameter

sendDraft(billnumber) {
    axios
      .post("http://192.168.0.111:3000/sendDraft", {
        invoice: billnumber,
      })
      .then((response) => {
        console.log(response);
      });
  }

That is the function which will send the parameter to sendDraft function

let drafts = this.state.invoice.map((invc) => {
      return (
        <Card key={invc.invoiceId}>
          <Card.Title>Invoice Number: {invc.billnumber}</Card.Title>
          <Card.Divider />
          <View>
            <Text>
              Customer's address:
              {invc.address}
            </Text>
            <Text>Customer's email: {invc.email}</Text>
            <Text>Total Price: {invc.price}</Text>
          </View>
          <Button //Button which will be pressed to send parameter
            title="SEND DRAFT"
            onPress={this.sendDraft.bind(this, invc.billnumber)}
          />
        </Card>
      );
    });

That is the button (the last Button)

I am sure that invc.billnumber is not null.

but when I click the button the variable is not passed and the update statement wont find the record.

(API works perfectly in postman).

What is the problem and how do we pass variables in react native.

To confirm that the invc.billnumber is not null or undefined you have to debug them. Console it before return to check whether invc.billnumber is not null or undefined.

console.log(invc.billnumber);

Second issue might be with the binding where you are implementing onPress event. You can do the binding in the constructor by using ES6 syntax:

export default class Abc extends Component {
  constructor(props) {
    super(props);
    this.sendDraft= this.sendDraft.bind(this);
  }

And then:

let drafts = this.state.invoice.map((invc) => {
      console.log(invc.billnumber); //To check invc.billnumber value
      return (
        <Card key={invc.invoiceId}>
          <Card.Title>Invoice Number: {invc.billnumber}</Card.Title>
          <Card.Divider />
          <View>
            <Text>
              Customer's address:
              {invc.address}
            </Text>
            <Text>Customer's email: {invc.email}</Text>
            <Text>Total Price: {invc.price}</Text>
          </View>
          <Button
            title="SEND DRAFT"
             onPress={() => this.sendDraft(invc.billnumber)}> //Bind like this
          />
        </Card>
      );
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM