如何在react native中调用函数内部的组件

问题描述 投票:0回答:1

我正在尝试使用react native来创建一个应用程序。我正在使用博览会。我有一个名为DistList的组件,应根据对象中条目的数量重复调用该组件。但是,在forEach中使用该组件时不会调用

HomeData.js

import React from 'react';
import { StyleSheet, Text, View, SafeAreaView, Platform, StatusBar, ScrollView, Dimensions } from 'react-native';

import dataCovid from '../store/dataCovid.json'
import DataList from './DataList.js'
import colors from './config/colors.js'


export default class HomeData extends React.Component{
  constructor(props) {
    super(props);


    this.state = {
      dataSource : '',
      currentTotal : 0,
      currentRecovered : 0,
      currentDecreased : 0,
      currentActive : 0,
    }
 }

fetchUsers(){
  fetch("https://api.covidindiatracker.com/state_data.json")
    .then(response => response.json())
    .then((responseJson)=> {
      this.setState({
       loading: false,
       dataSource: responseJson
      })

    })
    .catch(error=>console.log(error)) //to catch the errors if any
    // console.log(responseJson)
    // this.calculateCount();

}

  componentDidMount(){
    this.fetchUsers();
  }

  /* componentDidUpdate(){
    this.calculateCount();
  } */

    calculateCount(){
      console.log("cc")
      // console.log("cclen", this.state.dataSource)
      // console.log("cclen", this.state.dataSource.length)
      if(this.state.dataSource.length > 0){
        let data = /* JSON.stringify( */this.state.dataSource;
        // console.log(data)

        // if(recoveredResult == 0||decreasedResult == 0||activeResult == 0){
          console.log("inside")
        // var dataValue = Array.from(data)
        // var activeResult = data.map(activeVal => activeVal.active).reduce((nextValue, activeVal) => activeVal + nextValue);
        var recoveredResult = data.map(activeVal => activeVal.recovered).reduce((nextValue, activeVal) => activeVal + nextValue);
        var decreasedResult = data.map(activeVal => activeVal.deaths).reduce((nextValue, activeVal) => activeVal + nextValue);
        var activeResult = data.map(activeVal => activeVal.active).reduce((nextValue, activeVal) => activeVal + nextValue);
        var totalResult = recoveredResult+decreasedResult+activeResult;
        console.log(recoveredResult)
        console.log(decreasedResult)
        console.log(activeResult)

          this.setState({
            currentTotal : totalResult,
            currentRecovered : recoveredResult,
            currentDecreased : decreasedResult,
            currentActive : activeResult,
          })
        // }
        console.log(recoveredResult)
        console.log(this.state.currentRecovered)
        console.log(this.state.currentDecreased)
        console.log(this.state.currentActive)
      }
    }


    handleDataList=()=>{
      console.log("asdasd", this.state.dataSource.length)
      if(this.state.dataSource.length > 0){
        this.state.dataSource.forEach(function(element){
          console.log(element);
          return (
          <View>
          <DataList 
            state={element.state} 
            recovered={element.recovered} 
            decreased={element.deaths} 
            total= {element.confirmed+element.recovered+element.deaths+element.active}
            heading={true}
            />
            </View>
            );
      });
      }
    }


  render() {
    // console.log("erer", this.state.dataSource)
    // console.log("erer", this.state.currentRecovered)
    // console.log("erer", JSON.stringify(dataCovid) )
    if(this.state.currentActive == 0){
      this.calculateCount();
    }
    return (
        <View style={styles.container}>
      {/* <ScrollView> */}
          <View style={styles.containerTop}>
            <View style={styles.totalContainerOne}>
              <Text style={[styles.textStyle, styles.textTotal, ]}>Total</Text>
              <Text>[{this.state.currentTotal}]</Text>
            </View>
            <View style={styles.totalContainerTwo}>
              <View style={styles.recoveredContainer}>
                <Text style={[styles.textStyle, styles.textRecovered, ]}>Recovered</Text>
                <Text>[{this.state.currentRecovered}]</Text>
              </View>
              <View style={styles.decreasedContainer}>
                <Text style={[styles.textStyle, styles.textDecreased, ]}>Decreased</Text>
                <Text>[{this.state.currentDecreased}]</Text>
              </View>
              <View style={styles.activeContainer}>
                <Text style={[styles.textStyle, styles.textActive, ]}>Active</Text>
                <Text>[{this.state.currentActive}]</Text>
              </View>
            </View>
          </View>
          <View style={styles.containerBottom}>
            <DataList state="State" total="Total" recovered="Recovered" decreased="Decreased" heading={true}/>
            <DataList state="State" total="Total" recovered="Recovered" decreased="Decreased" heading={true}/>

              {
                this.handleDataList()

              }

          </View>
      {/* </ScrollView> */}
        </View>
    );
}
}

const styles = StyleSheet.create({
  container: {
    // width : '100%',
    // flex: 1,
    // height : '100%',
    // height: 1500,
    // flexDirection : 'row',
    // backgroundColor: 'blue',
    // alignItems: 'center',
    // justifyContent: 'space-evenly',
    // marginTop : Platform.OS === 'android' ? StatusBar.currentHeight : 0,
    // elevation : 5
  },

  containerTop: {
    // flex: 0.3,
    // height : '15%',
    height: Dimensions.get('window').height/3,
    // flexDirection : 'row',
    // backgroundColor: 'blue',
    alignItems: 'center',
    justifyContent: 'space-evenly',
    // marginTop : Platform.OS === 'android' ? StatusBar.currentHeight : 0,
    // elevation : 5
  },
  totalContainerOne: {
    height : '45%',
    // flex: 0.8,
    width : '90%',
    backgroundColor: '#eeeeee',
    elevation : 20,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius : 15,

  },
  textTotal:{
    color : colors.totalColor,
  },
  totalContainerTwo: {
    // flex: 0.8,
    width : '100%',
    height : '45%',
    // backgroundColor: 'green',
    flexDirection : 'row',
    justifyContent : 'space-evenly'
  },
  recoveredContainer: {
    // flex: 1,
    width : '30%',
    // height : '45%',
    backgroundColor: '#eeeeee',
    elevation : 50,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius : 15,
  },
  textRecovered:{
    color : colors.recoveredColor,
  },
  decreasedContainer: {
    // flex: 1,
    width : '30%',
    // height : '45%',
    backgroundColor: '#eeeeee',
    elevation : 50,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius : 15,
  },
  textDecreased:{
    color : colors.decreasedColor,
  },
  activeContainer: {
    // flex: 1,
    width : '30%',
    // height : '45%',
    backgroundColor: '#eeeeee',
    elevation : 50,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius : 15,
  },
  textActive:{
    color : colors.activeColor,
  },
  textStyle:{
    fontSize : 18,
    fontWeight : '700',
  },

  containerBottom: {
    paddingTop : 10,
    // flex: 0.4,
    // height:'85%',
    // flexDirection : 'row',
    // backgroundColor: 'blue',
    alignItems: 'center',
    justifyContent: 'space-evenly',
    // marginTop : Platform.OS === 'android' ? StatusBar.currentHeight : 0,
    // elevation : 5
  },
});

DataList.js

import React from 'react';
import { StyleSheet, Text, View, SafeAreaView, Platform, StatusBar, ScrollView, Dimensions } from 'react-native';

import dataCovid from '../store/dataCovid.json'
import colors from './config/colors.js'


export default class DataList extends React.Component{
  constructor(props) {
    super(props);

    this.state = {
    }
 }
  render() {
      const {state, total, recovered, decreased, heading} = this.props;
      const testStyle = (heading)? styles.testHeadingStyle : styles.dataStyle
    return (
        <View style={styles.container}>
            <View style={styles.stateBox}>
                <Text style={testStyle}>{state}</Text>
            </View>
            <View style={styles.stateBox}>
                <Text style={testStyle}>{total}</Text>
            </View>
            <View style={styles.stateBox}>
                <Text style={testStyle}>{recovered}</Text>
            </View>
            <View style={styles.stateBox}>
                <Text style={testStyle}>{decreased}</Text>
            </View>
        </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    width : '100%',
    flex: 1,
    // height : '100%',
    // height: 1500,
    flexDirection : 'row',
    // backgroundColor: 'blue',
    alignItems: 'center',
    justifyContent: 'space-evenly',
    // marginTop : Platform.OS === 'android' ? StatusBar.currentHeight : 0,
    // elevation : 5
  },
  stateBox:{
    height : 30,
    width : 87,
    backgroundColor : '#f6f6f7',
    borderRadius : 5,
    // top : 5,
    justifyContent : 'center',
    // alignItems : 'center',
    elevation : 5,
    textAlign : 'left',
    paddingLeft : 5,


  },
  testHeadingStyle:{
    fontSize : 15,
    fontWeight : '700',
    color : '#6c757d',
    textShadowColor: 'rgba(0, 0, 0, 0.50)',
    textShadowOffset: {width: -1, height: 1},
    textShadowRadius: 10,
  },
  dataStyle:{
    fontSize : 15,
    fontWeight : '700',
    color : '#6c757d',
    // textShadowColor: 'rgba(0, 0, 0, 0.50)',
    // textShadowOffset: {width: -1, height: 1},
    // textShadowRadius: 10,
  }
});

我正在使用此函数handleDataList()来调用forEach中的DistList.js组件。但是调用组件在这里不起作用。有人可以帮忙吗?

javascript reactjs react-native
1个回答
1
投票
  {
                this.handleDataList()

              }

您可以执行此操作,在渲染器内部创建一个函数,它将渲染该函数将返回的所有内容,可以是一些html代码段或组件。

但是您需要确保handleDataList()返回某些内容

handleDataList=()=>{
      console.log("asdasd", this.state.dataSource.length)
      if(this.state.dataSource.length > 0){
        this.state.dataSource.forEach(function(element){
          console.log(element);
          return (
          <View>
          <DataList 
            state={element.state} 
            recovered={element.recovered} 
            decreased={element.deaths} 
            total= {element.confirmed+element.recovered+element.deaths+element.active}
            heading={true}
            />
            </View>
            );
      });
      }
    }

这将返回未定义。

您可能会认为它将返回

return (
          <View>
          <DataList 
            state={element.state} 
            recovered={element.recovered} 
            decreased={element.deaths} 
            total= {element.confirmed+element.recovered+element.deaths+element.active}
            heading={true}
            />
            </View>
            );

但不是,因为此返回是forEach函数回调的返回,但这根本不会影响handleDataList

handleDataList=()=>{
      console.log("asdasd", this.state.dataSource.length)
      if(this.state.dataSource.length > 0){
        return this.state.dataSource.map(function(element){
          console.log(element);
          return (
          <View>
          <DataList 
            state={element.state} 
            recovered={element.recovered} 
            decreased={element.deaths} 
            total= {element.confirmed+element.recovered+element.deaths+element.active}
            heading={true}
            />
            </View>
            );
      });
      }
    }

应该返回。

热门问题
推荐问题
最新问题