React Native List and Grid-如何实现图标的活动颜色

时间:2019-07-03 11:57:04

标签: react-native react-native-vector-icons

我正在尝试为单击的图标(“列表”和“网格”)应用有效颜色,但是由于RN中的新特性,因此找不到正确的解决方案。我已经分别粘贴了组件代码以供他人参考。

代码:

export default class Gallery extends Component {
  state = {
    loading: true,
    gridView: true,
    iconColor: "#ccc"
  };

  changeViewList = () => {
    this.setState({ gridView: false });
  };
  changeViewGrid = () => {
    this.setState({ gridView: true });
  };

  render() {
    const { imageData, loading } = this.state;
    return (
      <View style={{ flex: 1 }}>
          <TouchableOpacity activeOpacity={0.8} onPress={this.changeViewGrid}>
              <Icon name="th-large" size={25} color={this.state.iconColor} />
           </TouchableOpacity>
           <TouchableOpacity activeOpacity={0.8} onPress={this.changeViewList}>
             <Icon name="list" size={25} style={styles.iconAlign} color= {this.state.iconColor} />
           </TouchableOpacity>
          </View>
    );
  }
}

const styles = StyleSheet.create({
  btnDesign: {
    padding: 10,
    backgroundColor: "#e45",
    width: "30%",
    alignSelf: "center",
    marginBottom: 10
  },
  btnText: {
    color: "#fff",
    textAlign: "center",
    alignSelf: "center"
  }
});

图片参考:

app image

预期为:

列表视图

enter image description here

网格视图 enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用color prop中的三元运算符根据变量对图标着色。

// if the this.state.gridView is true colorize the icon green otherwise take the standard color 
<Icon name="th-large" size={25} color={this.state.gridView ? 'green' : this.state.iconColor } />

在这里您可以用另一种方法来做:

// if this.state.gridView is true, take the regular color otherwise use make it green 
<Icon name="list" size={25} style={styles.iconAlign} color= {this.state.gridView ? this.state.iconColor : 'green' } />