【问题标题】:How to return value from function call by button onpress?如何通过按钮onpress从函数调用中返回值?
【发布时间】:2019-08-17 11:55:16
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reactjs button native onpress


    【解决方案1】:

    您实际上不会从 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>
       );
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-13
      相关资源
      最近更新 更多