如何更改react-native GridView组件中的可见性状态?

时间:2016-12-01 10:29:06

标签: gridview react-native

我正在研究react-native GridView组件,我想更改GridView项目点击的可见性状态。

所以我有一个列表颜色网格,但是当我点击单个项目时,它应该选择并显示一个刻度线。

网格项

enter image description here

选择

上的网格项目

enter image description here

代码:

export default class filter extends Component {
   constructor() {
     super();
      this.state = {
           gridDataSourceColor: filterColor,
           isVisible: false,
     };
   }
render() {
     return (
        <View>
            <GridView
               items={this.state.gridDataSourceColor}
               itemsPerRow={6}
               renderItem={this.renderColorItem.bind(this)}
            />
        </View>
     );
}

onItemPressed(item){

}

renderColorItem(item){
  return(
    <TouchableHighlight key={item.id} onPress={this.onItemPressed.bind(this, item)}>
        <View 
            key={item.id} 
            style={{
                width: 50,
                height: 45,
                marginLeft: 2,
                marginRight: 2,
                justifyContent: 'center',
                alignItems: 'center',
                marginTop: 5,
                backgroundColor: item.color}}>

                <Image 
                    style={{
                        width: 25,
                        height:25}} 
                    source={require('../images/check_mark_icon.png')} />
        </View>
    </TouchableHighlight>
  );
 }
}

所以在上面的代码中,当我执行onItemPressed()时,它应该改变状态并显示刻度线。

请仔细阅读我的帖子并向我推荐一些解决方案。

1 个答案:

答案 0 :(得分:2)

isSelected的项目中取filterColor

onItemPressed(item){
 var tempFilterColor = this.state.gridDataSourceColor;
   for (var i=0; i< tempFilterColor.length; i++)
   {
         if (tempFilterColor[i].id == item.id) {
        tempFilterColor[i].isSelected = true;
        break; //Stop this loop, we found it!
     }
   }
   this.setState({ gridDataSourceColor : tempFilterColor}); 
}

renderColorItem(item){
  return(
    <TouchableHighlight key={item.id} onPress={this.onItemPressed.bind(this, item)}>
        <View 
            key={item.id} 
            style={{
                width: 50,
                height: 45,
                marginLeft: 2,
                marginRight: 2,
                justifyContent: 'center',
                alignItems: 'center',
                marginTop: 5,
                backgroundColor: item.color}}>

                {this.renderCheckMark(item)}
        </View>
    </TouchableHighlight>
  );
 }

 renderCheckMark(item)
 {
    if(item.isSelected) { // image render only if item selected
        return(
        <Image 
                    style={{
                        width: 25,
                        height:25}} 
                    source={require('../images/check_mark_icon.png')} />
        );
    }
 }