在React Native Pro中传递函数

时间:2018-08-15 15:58:06

标签: react-native dynamic prop

我目前有一个屏幕,上面列出了带有星级的项目。

enter image description here

之所以创建此文件,是因为_renderItem函数为FlatList组件返回了以下JSX。 :

      <TouchableOpacity
    delayPressIn={70} 
    activeOpacity={0.8}
    onPress={() => {
      navigate("WellbeingBreakdown", {
        id: info.item.id,
      });
    }}
  >

    <RkCard rkType="horizontal" style={styles.card}>
      <Image
        rkCardImg
        source={info.item.icon}
      />

      <View rkCardContent>
        <RkText rkType="small">{info.item.title}{' '}<Ionicons name="ios-information-circle-outline" size={18} color="gray"/></RkText> 


        <View style={{flexDirection: 'row', paddingVertical: 10}}>

         <Rating
        type='custom'
        onFinishRating={this.ratingCompleted}
        imageSize={20}
        ratingColor={RkTheme.current.colors.primary}
        ratingImage={STAR_IMAGE}
        style={{paddingVertical: 8}}
        startingValue={2} /*I want to change this to be dynamic */

        />

        <RkButton 
        rkType="rounded small"
        style={{backgroundColor: RkTheme.current.colors.primary, marginLeft: 15}}
        onPress={() => navigate("DynamicActivityAssessor", {
          id: info.item.title
        }) 
      }

        >Assess</RkButton>

        </View>
      </View>
    </RkCard>
  </TouchableOpacity>

我想做的是动态地(从API中)获取数据,并将用户对每个商品的评分传递到 Rating 组件的startingValue属性中。

如果被调用,API将返回一个数组。因此,访问response [0]将为您提供与此类似的对象(值取决于其活动性或饮食等级等):

{
    "ActivityTotalScore": null,
    "DietTotalScore": 1,



},

所以我认为大致上像这样的功能会起作用,但我不知道如何将其传递给该道具。注意-info.item.id是相关渲染项目的标题。因此等于“运动”或“体重”等

  getScore(info){

fetch(`${server_url}data/Wellbeing?where=type%3D`+info.item.id, {

    method: "GET", // or 'PUT'  // data can be `string` or {object}!
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(res => res.json())
    .catch(error => console.error("Error:", error))
    .then(response => {


     return response[0][info.item.id+'TotalScore'] ;

      }
    )

}

1 个答案:

答案 0 :(得分:0)

简单的方法是创建一个代表您的卡的新组件。可能是

// In AssessCard.js
import React from 'react';
// Others imports

export default class AssessCard extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            rating: 0,
            item: props.item
        };
    }

    componentDidMount() {
        this._loadRating();
    }

    _loadRating() {
        fetch(`${server_url}data/Wellbeing?where=type%3D`+info.item.id, {

    method: "GET", // or 'PUT'  // data can be `string` or {object}!
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(res => res.json())
    .catch(error => console.error("Error:", error))
    .then(response => {
         this.setState({ rating: response[0][info.item.id+'TotalScore'] }); // HERE WE'RE SAVING THE RATING

      }
    )
    }

    render() {
        const { rating, item } = this.state;

        return (
            <TouchableOpacity
    delayPressIn={70} 
    activeOpacity={0.8}
    onPress={() => {
      navigate("WellbeingBreakdown", {
        id: item.id,
      });
    }}
  >

    <RkCard rkType="horizontal" style={styles.card}>
      <Image
        rkCardImg
        source={item.icon}
      />

      <View rkCardContent>
        <RkText rkType="small">{item.title}{' '}<Ionicons name="ios-information-circle-outline" size={18} color="gray"/></RkText> 


        <View style={{flexDirection: 'row', paddingVertical: 10}}>

         <Rating
        type='custom'
        onFinishRating={this.ratingCompleted}
        imageSize={20}
        ratingColor={RkTheme.current.colors.primary}
        ratingImage={STAR_IMAGE}
        style={{paddingVertical: 8}}
        startingValue={rating} // HERE WE USE RATING PROP OF THIS COMPONENT

        />

        <RkButton 
        rkType="rounded small"
        style={{backgroundColor: RkTheme.current.colors.primary, marginLeft: 15}}
        onPress={() => navigate("DynamicActivityAssessor", {
          id: item.title
        }) 
      }

        >Assess</RkButton>

        </View>
      </View>
    </RkCard>
  </TouchableOpacity>
);
    }

}

//in file contening your _renderItem function
import AssessCard from './somewhere/AssessCard';
/* CODE */

    _renderItem (info) => {
        return <AssessCard item={info.item} />
    }