reactjs 在React Native中更改TouchableOpacity的颜色

kuhbmx9i  于 12个月前  发布在  React
关注(0)|答案(5)|浏览(159)

谁能帮帮我。这是我的源代码:https://snack.expo.io/rJFgyPDpH
想法是,如果我点击“1按钮”,它应该是“红色”,如果我点击**“2按钮”也应该将其颜色更改为“红色”,但“1按钮”应该更改为默认颜色,即黑色。但是,“2按钮”**。
如果我的方法太简单,也欢迎其他方法(如TouchableHighlight,ES6等)。我很感激你能指出我的错误,让我从中吸取教训。

gjmwrych

gjmwrych1#

试试下面

state={
    selectedButton: '',
};

      <View style={styles.container}>
          <TouchableOpacity
              style={{ backgroundColor: this.state.selectedButton === 'button1' ? 'red' : 'black', padding: 15}}
              onPress={() => this.setState({ selectedButton: 'button1' })}
          >
            <Text style={styles.text}>1 Button</Text>
          </TouchableOpacity>

          <TouchableOpacity
              style={{ backgroundColor: this.state.selectedButton === 'button2' ? 'red' : 'black', padding: 15}}
              onPress={() => this.setState({ selectedButton: 'button2' })}
          >
            <Text style={styles.text}>2 button!</Text>
          </TouchableOpacity>

      </View>
b1uwtaje

b1uwtaje2#

你可以这样写代码:

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

export default class App extends Component {
  state={
    backgroundColor: 'black',
    backgroundColor2: 'black',
    pressed: false,
  };

  changeColor(){
    if(!this.state.pressed){
       this.setState({ pressed: true,backgroundColor: 'red', backgroundColor2: 'black'});
    } else {
      this.setState({ pressed: false, backgroundColor: 'black' ,backgroundColor2: 'red'});
    }
  }
  render() {
    return (
      <View style={styles.container}>
          <TouchableOpacity
              style={{backgroundColor:this.state.backgroundColor, padding: 15}}
              onPress={()=>this.changeColor()}
                >
            <Text style={styles.text}>1 Button</Text>
          </TouchableOpacity>

          <TouchableOpacity
              style={{backgroundColor:this.state.backgroundColor2, padding: 15}}
              onPress={()=>this.changeColor()}
                >
            <Text style={styles.text}>2 button!</Text>
          </TouchableOpacity>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  text:{
    color:'white'
    },
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
});

现在,如果你点击第一个按钮,它应该是“红色”,但第二,仍然是“黑色”的背景。因此,如果你点击第二个按钮,它应该是“红色”,而第一个按钮应该是“黑色”。

xoshrz7s

xoshrz7s3#

changeColor=()=>{
   this.setState({
      backgroundColor:'red',
      backgroundColor2:'black'
   })
 }

  changeColor2=()=>{
    this.setState({
       backgroundColor:'black',
       backgroundColor2:'red'
   })
 }

根据您的要求,按下第一个按钮,它将调用changeColor。按下第二个按钮,它将调用changeColor2。
在代码中,onPress第二个按钮,它可以改变为changeColor2而不是changeColor函数。

onPress={()=>this.changeColor2()}

而不是

onPress={()=>this.changeColor()}
gstyhher

gstyhher4#

通过传递id,你可以改变颜色

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

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = { colorId:0 };
  }
  onPress = (id) => {
    this.setState({colorId: id});
  };

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity
          style={this.state.colorId === 1? styles.red : styles.button}
          onPress={()=>this.onPress(1)}>
          <Text>Button1</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={this.state.colorId === 2? styles.red : styles.button}
          onPress={()=>this.onPress(2)}>
          <Text>Button2</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: 10,
  },
  red: {
    backgroundColor: 'red',
    alignItems: 'center',
    padding: 10,
  },
  button: {
    alignItems: 'center',
    backgroundColor: '#DDDDDD',
    padding: 10,
  },
});

Live demo

1l5u6lss

1l5u6lss5#

因此,所有当前的方法都使用onPress来管理状态。
如果您在以下位置查看文档:https://reactnative.dev/docs/touchableopacity
TouchOpacity组件继承了https://reactnative.dev/docs/touchablewithoutfeedback#props的所有属性
这意味着你可以访问onPressIn和onPressOut,我个人使用它们来管理状态,而不是onPress。
这是我可能过于复杂的例子,我也使用了阴影和渐变:

import React, {FC, FormEvent, ReactNode, useState} from 'react';
import {ActivityIndicator, GestureResponderEvent} from 'react-native';
import styled from '@emotion/native';
import LinearGradient from 'react-native-linear-gradient';
import DropShadow from "react-native-drop-shadow";
import {Theme, useTheme} from "@emotion/react";
import {adjustColor} from "../../helpers";

interface StyledProps {
  fullWidth?: boolean;
  variant?: string;
  activeVariant?: string;
  borderRadius?: string;
  width?: string;
  height?: string;
  padding?: string;
  fontSize?: string;
  fontWeight?: string;
  colors?: string[];
  gradient?: boolean;
  active?: boolean;
  isLoading?: boolean;
}

interface ButtonProps<T = GestureResponderEvent> extends StyledProps {
  onPress: ((event: T) => void) | undefined;
  children: ReactNode;
}

const dropShadowProps = {
  shadowColor: "#000",
  shadowOffset: {
    width: 0,
    height: 0,
  },
  shadowOpacity: .2,
  shadowRadius: 5
}

const Button: FC<ButtonProps> = (props) => {
  const theme = useTheme();
  const {onPress, isLoading, children, ...rest} = props;
  const [active, setActive] = useState<boolean>(false);

  const handleOnPress = (event: any) => {
    onPress && onPress(event);
  };

  return (
    <StyledButton {...rest}
      onPress={handleOnPress}
      onPressIn={() => setActive(true)}
      onPressOut={() => setActive(false)}
      activeOpacity={props.activeVariant ? 1 : 0.2}
      disabled={isLoading}
    >
      <DropShadow style={active ? {} : dropShadowProps}>
        <StyledGradient colors={getBackgroundColors(props, active, theme)} {...rest}>
          <StyledText {...rest} active={active}>
            {children}
            {isLoading ? (
              <ActivityIndicator color={"#000"} />
            ) : null}
          </StyledText>
        </StyledGradient>
      </DropShadow>
    </StyledButton>
  );
};

const getBackgroundColors = (props: StyledProps, active: boolean, theme: Theme) => {
  const variant = active && props.activeVariant ? props.activeVariant : props.variant;
  const colors = [];

  switch (variant) {
    case "primary":
      colors.push(theme.colors.primary);
      break;
    default:
      colors.push("#ffffff");
  }

  if (props.gradient) {
    colors.push(adjustColor(colors[0], -15));
  } else {
    colors.push(colors[0]);
  }

  return colors;
}

const getColor = (props: any) => {
  const variant = props.active && props.activeVariant ? props.activeVariant : props.variant;

  switch (variant) {
    case "primary":
      return props.theme.colors.white;
    default:
      return props.theme.colors.black;
  }
}

const StyledButton = styled.TouchableOpacity<StyledProps>`
  width: ${props => props.fullWidth ? "100%" : props.width ? props.width : "auto"};
`

const StyledGradient = styled(LinearGradient)<StyledProps>`
  width: ${props => props.fullWidth ? "100%" : props.width ? props.width : "auto"};
  height: ${props => props.height ? props.height : "auto"};
  border-radius: ${props => props.borderRadius ? props.borderRadius : "8px"};
  display: flex;
  justify-content: center;
  align-items: center;
`;

const StyledText = styled.Text<StyledProps>`
  color: ${props => getColor(props)};
  font-size: ${props => props.fontSize ? props.fontSize : "16px"};
  font-weight: ${props => props.fontWeight ? props.fontWeight : "400"};
  padding: ${props => props.padding ? props.padding : "17px"};
  line-height: ${props => props.fontSize ? props.fontSize : "16px"};
`

export default Button;

相关问题