简体   繁体   中英

How to return value from function call by button onpress?

I'm new to javascript family and I am writing a small program in react native. I am trying to SampleFunction2 to return census and render it on Flatlist when button onpress happens. Am I not supposed to return value for button onpress(event)? What is the correct approach? Thank you

    import React, { Component } from 'react';
    import { StyleSheet, FlatList,TouchableOpacity,Text, ListView,View, 
    Button, Alert } from 'react-native';
    export default class App extends Component<{}> {   

    SampleFunction2(){
     var census = [
                {name: 'Devin', id :0},
                {name:  'Jackson', id:1},
                {name:  'James', id:2},]


     return census;
   }

   render() {
    return (
      <View style={styles.container}>
      <Button onPress={this.SampleFunction2.bind(this)} title="Click here 
      to call function - One"
        //Here I was thinking I could overlay the return value into Flatlist
       />

      //<FlatList
      //<Button onPress={this.SampleFunction1.bind(this)} title= "Click 
        // here to call Function - One"/>
        //data = {this.SampleFunction2()}
       // renderItem = {({item}) =>
      //<Text>{item.id}</Text>,
       // <Text>{item.name}</Text>
     // }

     // />


      </View>
    );
  }

You dont actually return value from onPress, but you can set data to component state and show it if available. Following should work.

export default class App extends Component {   
  constructor() {
    this.state = {}
  }
  SampleFunction2(){
     this.setState({census: [
            {name: 'Devin', id :0},
            {name:  'Jackson', id:1},
            {name:  'James', id:2}]})
 }
 render() {
   const census = this.state.census;
   return (
     <View style={styles.container}>
       <Button onPress={this.SampleFunction2.bind(this)} title="Click here to call function - One" />

     {!census ? "" : (<FlatList data={census} renderItem={({item}) => <Text>{item.name}</Text>} />)}
     </View>
   );
 }

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