首页 > 解决方案 > 在反应原生道具中传递函数

问题描述

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

在此处输入图像描述

这是由于 FlatList 组件的 _renderItem 函数返回以下 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'] ;

      }
    )

}

标签: react-nativedynamicprop

解决方案


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

// 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} />
    }

推荐阅读