簡體   English   中英

如何僅更改活動按鈕背景顏色 [React-Native]

[英]How to change only the active button background color [React-Native]

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

class App extends Component {
  constructor(props){
    super(props)
    this.state={
      selected:null
    }
  }

  handle=()=>{
    this.setState({selected:1})
  }

  render() {
    return (
      <View>
        <TouchableOpacity style={[styles.Btn, {backgroundColor:this.state.selected===1?"green":"white"}]} onPress={this.handle}>
          <Text style={styles.BtnText}>Button 1</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.Btn} onPress={this.handle}>
          <Text style={styles.BtnText}>Button 2</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.Btn} onPress={this.handle}>
          <Text style={styles.BtnText}>Button 3</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  Btn: {
    borderWidth: 1,
    width: 100,
    height: 20,
    borderRadius: 8,
    margin: 5,
    padding: 10,

    justifyContent: 'center',
    flexDirection: 'row',
    alignItems: 'center',
  },

  BtnText: {
    fontSize: 15,
  },
});

export default App;

小吃鏈接: https://snack.expo.dev/U_fX-6Tao-

我想這樣做,所以當我單擊一個按鈕時,活動按鈕背景顏色應更改為“綠色”,文本更改為“白色”,並且按鈕 backgroundColor 和 textColor 的 rest 應保持“紅色”。 但是,當我單擊另一個按鈕時,該按鈕應該變為活動狀態,並且前一個活動按鈕應該恢復到正常的 state。

如果您還可以解釋其背后的邏輯,那就太好了,因為我是 React Native 的新手。

謝謝你。

您總是將活動按鈕設置為第一個。 另外,我會使用一個數組來呈現按鈕。 我會做這樣的事情:

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      selected: null
    }
  }

  handlePress = (item) => {
    this.setState({ selected: item })
  }

  render() {
    return (
      <View>
        {[...Array(3).keys()].map(item => (
          <TouchableOpacity key={item} style={[styles.Btn, {backgroundColor: this.state.selected === item ? "green" : "white" }]} onPress={() => this.handle(item)}>
            <Text style={styles.BtnText}>Button {item + 1}</Text>
          </TouchableOpacity>
        )}
      </View>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM