React Native开发星级评价组件,展示和选择(带思路),拿来就可以用

整体思路[根据自己的Angular4+开发经验而来,可能我写的代码有点偏向于Angular,不过思路更清晰, 同时我会把思路说的非常清楚, 我时刻明白, 如果你不能给一个三岁小孩子讲清楚,那么你就是不会.]

以下的思路, 可以用到任何框架上面, 同时用了width做了屏幕适配, 不会对原有项目代码造成任何影响, 请放心使用

比如Angular中 把ListView当成一个div, 把渲染换成*ngFor, 数据放到 constructor函数里面返回
比如 Vue 中, 把ListView当成一个div, 把渲染换成v-for, 数据放到 data函数里面返回,
比如 React 中, 把ListView当成一个div,直接用数组的一些遍历函数map一类都可以渲染出来组件, React和下面的代码差不多
星级评价组件预览


星级评价组件预览

如果你不想画上3分钟看思路, 那么最下面有代码可以直接用,

  • 星级展示思路
    传入值, 1-5 任意数字
    然后把把数字组成数组, 举例 假如传入的是4,那么会有一个这样的数组,也就是把值都变为true
[true, true, true, true, false] 

那么就可以根据这里面的值,改变组件的类名,从而改变了样式

具体实现

  1. 在constructor拿到传入的级别,类型是数字类型 int
  constructor(props) {
        super(props);
       // @param {星级,如果不传,默认是满级,值为5} this.props.rating
        this.rating = this.props.rating <= 5 && this.props.rating >= 0 ? this.props.rating : 5
}
  1. 导入RN组件,同时创建一个变量用来保存,ListView将要遍历的值
// 导入ListView
  import { ListView } from "react-native";
  constructor(props) {
        super(props);
        // @param {星级,如果不传,默认是满级,值为5} this.props.rating
        this.rating = this.props.rating <= 5 && this.props.rating >= 0 ? this.props.rating : 5
        // @param {是否可编辑,如果不传,默认是不可编辑,值为false} this.props.editable
        this.editable = this.props.editable ? this.props.editable : false
        // 定义准备被ListView包装的数组    this.ratingArr: Array<object> =[]
        this.ratingArr = []
       // 定义并声明 `ListView` 的包装函数  this.dSource: any
        this.dSource = (new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })) 
       // 定义被ListView的包装函数  this.dSource处理的数据,这个数据是用来渲染使用的
        this.state = { rating: this.dSource.cloneWithRows(this.ratingArr) }
    }
  1. 处理this.ratingArr的数据结构
      setRatingChange = () => {
        // 这里的星级是5级,如果你是其他星级,可以更改,
        this.ratingArr = Array.from({ length: 5 }).map((item, index) => {
        // 这句话的是,如果传入的等级小于或者等于index+1,
        // 那么才返回一个true, true代表的是点亮星星个数
            if (this.rating <= index + 1) {
                return {
                    status: true,
                    index,
                    // 索引都是0开始的, 因此需要增加1 
                    level: index + 1
                }
            } else {
                return {
                    status: false,
                    index,
                    level: index + 1
                }
            }
        })
    }
  1. this.state.rating 渲染到ListView中,特别强调[两点]
    • ListView的属性contentContainerStyle是用来写ListView样式的,其中,为了防止各种版本之间的缺陷,一点要写上样式flexWrap: "wrap"
    • RN的0.28版本的时候, 改变了内部代码, 从而,造成了, 需要定义即将渲染的元素的 alignItems"flex-start"
 render = () => {
        return (<View style={styles.vView}>
            <View style={[styles.vRatingV, styles.vRating_s]}>
                <ListView
                    contentContainerStyle={styles.vRating}
                    dataSource={this.state.rating}
                   // 这里是根据数组里的是否是true进行渲染不同的样式,
                   // 用了箭头函数, 代表直接return一个组件,采用的是JSX语法
                    renderRow={(item, index) => <Text
                    style={[styles.rating, this.rating < item.level ? styles.rating_n : ""]}>&#xe61d;</Text>}
                />
            </View>
        </View>)
    }

以上就是展示的代码完成了,

  • 星级选择思路
  1. 星级选择的思路也简单, 通过上面的星级展示思路, 想必也清楚了一个核心就是根据传入的星级的等级生成一个含有true,false的值
    因此,我们可以根据选择的是哪个星星, 根据该星星的索引对数组this.ratingArr = []重新计算值, 然后把ListView的dataSource的值进行重新赋值
  2. 我们增加一个点击函数事件
 render = () => {
        return (<View style={styles.vView}>
            <View style={[styles.vRatingV, styles.vRating_s]}>
                <ListView
                    contentContainerStyle={styles.vRating}
                    dataSource={this.state.rating}
                    renderRow={(item, index) => <Text
                   // 这里增加一个点击事件`this.selectStar`
                   // 参数是`item`和`index`, 用来进行选择
                    onPress={this.selectStar.bind(this, item, index)}
                    style={[styles.rating, this.rating < item.level ? styles.rating_n : ""]}>&#xe61d;</Text>}
                />
            </View>
        </View>)
    }

这里是添加的点击事件匿名变量函数

    selectStar = (item, Windex) => {
        this.rating = item.level
        this.setRatingChange()
        this.setState({ rating: this.dSource.cloneWithRows(this.ratingArr) })
    }
  1. 以上就完成了点击切换功能

怎么封装一个组件出去呢?

我们可以定义三个导入值, 为了防止报错,(比如没有传入值等), 我们需要定义三个具体的参数,用来说明,分别是
/**

  • @param {星级,如果不传,默认是满级,值为5} this.props.rating
  • @param {是否可编辑,如果不传,默认是不可编辑,值为false} this.props.editable
  • @param {接收的函数,如果不传递,那么不会传递出去,只会什么都不做} this.props.selectStar
    */
  1. 我们需要在初始化的时候处理这参数, 其中第三个参数this.props.selectStar可以放到使用的时候再判断,
        // @param {星级,如果不传,默认是满级,值为5} this.props.rating
        this.rating = this.props.rating <= 5 && this.props.rating >= 0 ? this.props.rating : 5
        // @param {是否可编辑,如果不传,默认是不可编辑,值为false} this.props.editable
        this.editable = this.props.editable ? this.props.editable : false
  1. 对是否能都编辑,进行判断, 如果传入了可以编辑,那么就不会使用
    this.editable的默认值
    同时,我们可以改造一下点击事件函数
    selectStar = (item, Windex) => {
        // 判断是否传入了可编辑
        if (this.editable == true) {
            this.rating = item.level
            this.setRatingChange()
            this.setState({ rating: this.dSource.cloneWithRows(this.ratingArr) })
            // 把值传递出去,如果为真,那么可以作为参数传递出去,如果为假,则无法传递出去
            this.props.selectStar ? this.props.selectStar(item.level) : ""
            return item.level
        } else {
            return false
        }
    }
  1. 我们可以定义一个最大星级
  • @param {最大星级,如果不传,默认是5,值为5} this.props.maxRating
  1. 如果父组件传入的是一个变量,或者用了很多的引用, 那么需要在子组件里面实时更改值,而不是第一次的时候就默认那样子了
   componentWillReceiveProps = (nextProps) => {
        this.maxRating = nextProps.maxRating ? nextProps.maxRating : 5
        this.rating = nextProps.rating ? (nextProps.rating >= 0 && nextProps.rating <= this.maxRating ? nextProps.rating : this.maxRating) : this.maxRating
        this.editable = nextProps.editable ? nextProps.editable : false
        this.props.selectStar = nextProps.selectStar ? nextProps.selectStar : null
        this.initPage()
    }

我们最后封装封装代码优化一下,这样子的代码看着才更简洁, 下面附代码,

使用的使用,直接

    import Rating from "./rating"
.....N多代码
    render = () =>{
        return (<View>
                        <Rating rating={this.state.companyDetail.rating ? this.state.companyDetail.rating / 10 : 5}></Rating>
                </View>)
        }
    

github源码

/*
 * @Description: 星级评论组件
 * @version: 0.1.0
 * @Company: 
 * @Author: AmandaYi
 * @Date: 2018-10-25
 * @LastEditors: AmandaYi
 * @LastEditTime: 2018-10-25 
 */
/**
 * @param {最大星级,如果不传,默认是5,值为5} this.props.maxRating
 * @param {星级,如果不传,默认是满级,值为5} this.props.rating
 * @param {是否可编辑,如果不传,默认是不可编辑,值为false} this.props.editable
 * @param {接收的函数,如果不传递,那么不会传递出去,只会什么都不做} this.props.selectStar
 */
import React, { Component } from "react";
import { View, Text, StyleSheet, ListView } from "react-native";
import globalStyle, {
    width,
    rx
} from "./variable"
const styles = StyleSheet.create({
    vView: {
        position: "relative"
    },
    vRating: {
        flexDirection: "row",
        flexWrap: "wrap",
        width,
    },
    vRatingV: {
        position: "absolute",
        top: 0,
        left: 0,
    },
    vRating_s: {
        zIndex: 1000
    },
    vRating_n: {
        zIndex: 800
    },
    rating: {
        fontFamily: "iconfont",
        fontSize: rx(34),
        color: '#ff6600',
        marginRight: rx(10),
        backgroundColor: "#ffffff",
        alignItems: "flex-start",

    },
    rating_n: {
        color: '#cccccc',
    }
})
export default class Rating extends Component {
    constructor(props) {
        super(props);
        // 定义总星级
        this.maxRating = this.props.maxRating ? this.props.maxRating : 5
        // @param {星级,如果不传,默认是满级,值为5} this.props.rating
        this.rating = this.props.rating <= this.maxRating && this.props.rating >= 0 ? this.props.rating : this.maxRating
        // @param {是否可编辑,如果不传,默认是不可编辑,值为false} this.props.editable
        this.editable = this.props.editable ? this.props.editable : false
        this.ratingArr = []
        this.dSource = (new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }))
        this.initPage()
        this.state = { rating: this.dSource.cloneWithRows(this.ratingArr) }
        this.props.selectStar = null
    }
    selectStar = (item, Windex) => {
        // 判断是否传入了可编辑
        if (this.editable == true) {
            this.rating = item.level
            this.setRatingChange()
            this.setState({ rating: this.dSource.cloneWithRows(this.ratingArr) })
            // 把值传递出去,如果为真,那么可以作为参数传递出去,如果为假,则无法传递出去
            this.props.selectStar ? this.props.selectStar(item.level) : ""
            return item.level
        } else {
            return false
        }
    }
    componentWillReceiveProps = (nextProps) => {
        this.maxRating = nextProps.maxRating ? nextProps.maxRating : 5
        this.rating = nextProps.rating ? (nextProps.rating >= 0 && nextProps.rating <= this.maxRating ? nextProps.rating : this.maxRating) : this.maxRating
        this.editable = nextProps.editable ? nextProps.editable : false
        this.props.selectStar = nextProps.selectStar ? nextProps.selectStar : null
        this.initPage()
    }
    // 处理函数
    initPage = () => {
        this.setRatingChange()
    }
    // 改变状态
    setRatingChange = () => {
        this.ratingArr = Array.from({ length: this.maxRating }).map((item, index) => {
            if (this.rating <= index + 1) {
                return {
                    status: true,
                    index,
                    level: index + 1
                }
            } else {
                return {
                    status: false,
                    index,
                    level: index + 1
                }
            }
        })
    }
    render = () => {
        return (<View style={styles.vView}>
            <View style={[styles.vRatingV, styles.vRating_s]}>
                <ListView
                    contentContainerStyle={styles.vRating}
                    dataSource={this.state.rating}
                    renderRow={(item, index) => <Text
                        onPress={this.selectStar.bind(this, item, index)}
                        style={[styles.rating, this.rating < item.level ? styles.rating_n : ""]}>&#xe61d;</Text>}
                />
            </View>
        </View>)
    }
}

注意点, 一定要更改适配文件的UI设计稿的宽度,默认是750,具体可以看代码

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,372评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,368评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,415评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,157评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,171评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,125评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,028评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,887评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,310评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,533评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,690评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,411评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,004评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,812评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,693评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,577评论 2 353

推荐阅读更多精彩内容

  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,441评论 1 33
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,071评论 25 707
  • 全球变暖,夏天越发燥热,我居住着的古都长安突破了40°的高温,一出超市树下的风都带着黏腻腻的汗味,真想对着太阳来...
    小北尾阅读 927评论 0 0
  • 电瓶车和方便面,是最近微博上的两个热点。从评论看,大家都很高大上,感觉不是一个世界。 先说方便面,因为一个争吵视频...
    花椒树阅读 419评论 0 0
  • 偶尔 想起了你,不知 你现在是否还安好 昨天的日子 如云烟 遮挡了望眼 虽然时间过去了那么久 但是你依然是我 没有...
    利君理疗阅读 90评论 0 0