0

我是 javascript 家族的新手,我正在编写一个反应原生的小程序。我正在尝试 SampleFunction2 返回人口普查并在按钮按下时将其呈现在 Flatlist 上。我不应该为按钮 onpress(事件)返回值吗?什么是正确的方法?谢谢

    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>
    );
  }
4

1 回答 1

0

您实际上并没有从 onPress 返回值,但您可以将数据设置为组件状态并在可用时显示它。以下应该工作。

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>
   );
 }
于 2019-03-27T01:17:36.757 回答