自定义星星组件

 

  // 星星点击后的回调事件,改变数据
  selectIndex = (count, row) => {
    this.state.data[row].SchScore = count
    this.modifyShowInput(row)
  }

import React, {Component} from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  Image,
  StyleSheet,
} from 'react-native'

class FiveStarsLayout extends Component {

  state = {
    totalCount: this.props.totalCount, // 总共的星星数量
    selectedCount: this.props.selectedCount, // 被选择的星星数量
    commentsList:  this.props.list || ['','要加油', '要加油', '还不错', '较好', '非常棒'],
    commentsTxt: '',
  }

  async componentWillReceiveProps(props) {
    await this.setState({
      totalCount: props.totalCount, // 总共的星星数量
      selectedCount: props.selectedCount, // 被选择的星星数量
    })
    if (this.state.selectedCount >= 0) {
      this.setState({
        commentsTxt: this.state.commentsList[this.state.selectedCount]
      })
    }else{
      this.setState({
        commentsTxt: this.state.commentsList[0]
      })
    }
  }

  // 星星的点击事件
  score = (i) => {
    console.log('i = ',i)
    if( i === 1 && this.state.selectedCount === 1){
      this.setState({
        selectedCount: 0,
        commentsTxt: this.state.commentsList[0]
      })
    }else{
      this.setState({
        selectedCount: i,
        commentsTxt: this.state.commentsList[i]
      })
    }

    this.props.selectIndex(i, this.props.row) // 回调给父组件
  }

  // 初始化星星的图片
  renderStarImage = (count) => {
    if (count <= this.state.selectedCount) {
      return ()
    }
    return ()

  }

  // 初始化星星布局
  renderItem = () => {
    const images = []
    for (let i = 1; i <= this.state.totalCount; i += 1) {
      const currentCount = i
      images.push(
         {
                            this.score(currentCount)
                          }}
                          style={i === 1?{marginLeft:0}:{marginLeft: 5}} activeOpacity={1}>

          {this.renderStarImage(i)}
        
      )
    }

    return {images}
  }

  render() {
    return (
      
        {this.renderItem()}
        {this.state.commentsTxt}
      
    )
  }


}

const styles = StyleSheet.create({
  commentsTxt: {
    marginLeft: 30,
    fontSize:14,
    color: '#b4b4b4'
  },
  textInput: {
    marginTop:5,
    marginLeft: 5,
    marginRight:22,
    fontSize:14,
    color: '#777777',
  },
})
export default FiveStarsLayout

FiveStarsLayout 传递props 初始化星星界面
初始化星星布局 image为数组 push几个可点击的TouchableOpacity的view

你可能感兴趣的:(自定义星星组件)