reactjs - 如何在 React 映射组件上进行独立样式更改
问题描述
当我尝试更改映射的 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 时,它们的背景颜色都会改变。
我想只定位一个并同时重置另一个
解决方案
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'
}
});
推荐阅读
- javascript - 如何在另一页上查看一个页面上的图像?
- java - java pgp用asc文件中的公钥加密文件
- css - .css 未加载,因为它的 MIME 类型“text/html”不是“text/css”。和 SyntaxError:预期的表达式,得到 '<'
- python - SARIMAX 没有结果
- mongodb - CosmosDB - Mongodb IsUpsert 不适用于批量更新
- reactive-programming - 反应式扩展最基本的运算符是什么?
- c++ - 在 C++ 中编写初始化类
- plot - 较低的时间框架成交量条
- python - 在分隔符旁边拆分字符串
- javascript - 播放视频或 gif 10 秒,暂停,单击按钮,播放 3 秒并跳转到视频中的另一个时间戳并播放设定的持续时间