尝试更改映射的TouchableOpacity的样式时遇到问题。
我映射了一个TouchableOpacity列表,当我单击一个列表时,我希望backgroundColor更改(黑色)仅在我单击的按钮上发生,而且还可以重置我之前单击的另一个TouchableOpacity的backgroundColor。
例如,如果我单击第一个TouchableOpacity,则该背景变为黑色。然后,如果我单击第二个,则第二个的背景变为黑色,但第一个的背景再次变为灰色。
export default class Playground extends Component {
state = {
isPressed: false
};
handlePress = () => {
this.setState({
isPressed: !this.state.isPressed
});
};
render() {
let array = [0, 1, 2];
return (
<View style={styles.container}>
<Text>Test</Text>
{array.map(item => {
return (
<TouchableOpacity
key={item}
style={this.state.isPressed ? styles.buttonPressed : styles.button}
onPress={this.handlePress}
>
<Text>Click on it</Text>
</TouchableOpacity>
);
})}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
marginTop: 50
},
button: {
backgroundColor: 'grey'
},
buttonPressed: {
backgroundColor: 'black'
}
});
这是我尝试过的方法,但是当我单击一个TouchableOpacity时,所有它们的backgroundColor都会更改。
我只想定位一个并同时重置另一个
答案 0 :(得分:0)
it's good working
[import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
export default class Playground extends Component {
state = {
isPressed: false
};
handlePress = () => {
this.setState({
isPressed: !this.state.isPressed
});
};
render() {
let array = \[0, 1, 2\];
return (
<View style={styles.container}>
<Text>Test</Text>
{array.map(item => {
return (
<TouchableOpacity
key={item}
style={this.state.isPressed === false ? styles.buttonPressed : styles.button}
onPress={this.handlePress}
>
<Text>Click on it</Text>
</TouchableOpacity>
);
})}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
marginTop: 50
},
button: {
backgroundColor: 'grey'
},
buttonPressed: {
backgroundColor: 'black'
}
});
答案 1 :(得分:0)
不确定这是否是解决问题的最佳方法,但我发现使用直接操作的潜在解决方案
我首先为每个TouchableOpacity分配一个不同的引用,然后我将该引用作为目标并使用setNativeProps更改目标的样式
export default class Playground extends Component {
state = {
daySelected: null
}
handlePress = (day, i) => {
if (this.state.daySelected !== null) {
this.state.daySelected.setNativeProps({
backgroundColor: 'grey'
});
}
this.setState({
daySelected: day
});
day.setNativeProps({
backgroundColor: 'black'
});
};
render() {
let array = [0, 1, 2];
return (
<View style={styles.container}>
<Text>Test</Text>
{array.map(i => {
return (
<TouchableOpacity
key={i}
ref={thisItem => (this[`item-${i}`] = thisItem)}
style={styles.button}
onPress={() => this.handlePress(this[`item-${i}`], i)}
>
<Text>Click on it</Text>
</TouchableOpacity>
);
})}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
marginTop: 50
},
button: {
backgroundColor: 'grey'
}
});