【问题标题】:Pass function in react native prop在反应原生道具中传递函数
【发布时间】:2019-01-22 12:54:34
【问题描述】:

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

这是由于 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 prop。

如果调用 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'] ;

      }
    )

}

【问题讨论】:

  • 只需将硬编码的startingValue道具替换为info.item.rating(我只是假设键名是基于您的info.item.title的评级)
  • info 只是一个本地对象,类似于: { id: "Diet", title: "Diet", screen: "DynamicActivityAssessor", icon: require("../../assets /images/flaticon/diet1.jpg"), },

标签: react-native dynamic prop


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 1970-01-01
    • 2021-08-14
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    相关资源
    最近更新 更多