1

我正在尝试为单击的图标(列表和网格)应用活动颜色,但自从新进入 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"
  }
});

图片参考:

应用图片

预计将是:

列表显示

在此处输入图像描述

网格视图 在此处输入图像描述

4

1 回答 1

1

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

// 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' } />
于 2019-07-03T12:05:05.997 回答