我想在React Native中的按下操作中动态更改TouchableOpacity的背景颜色。
TouchableOpacity修改了不透明度(正如其名称所示)。 如果您想在触摸时更改背景颜色,请改用TouchableHighlight。
import React, { useState } from 'react';
import { StyleSheet, TouchableOpacity } from 'react-native';
const colours = ['red', 'orange', 'yellow', 'blue', 'green', 'indigo', 'violet'];
const getColour = () => colours[Math.floor(Math.random() * colours.length)];
const Button = props => {
const [colour, setColour] = useState(getColour());
const handleClick = () => { setColour(getColour()); }
return (
<TouchableOpacity style={[styles.button, { backgroundColor: colour }]} onPress={handleClick}></TouchableOpacity>
);
}
const styles = StyleSheet.create({
button: {
borderColor: 'black',
borderWidth: 1,
width: 50,
height: 50,
}
});
export default Button;
TouchableHighlight
代替,并使用underlayColor
属性。 - jose920405