reactjs - 在 React Native 中更改先前状态的样式属性
问题描述
目前我正在使用 useState 为每次单击的图像添加边框。当我单击图像时,它会正确地给我一个边框,但是当我单击另一个图像时,它会保留以前的图像状态并使其保持活动状态。我想要的是当我按下图像时,单击的前一个图像应该删除它的边框,新图像应该有边框。这是我到目前为止使用的代码,每次点击都会为图像添加一个边框:
const ListItem = (props) => {
const [background, setBackground] = useState(true);
const setStyle = (background) => {
setBackground(background);
}
const { itemWidth } = props;
return (
<TouchableWithoutFeedback>
<Animated.View
style={{
margin: 5,
}}>
<View onClick={() => setBackground(current => !current)}
style={{borderWidth: background? 0:1,
borderColor: '#000',}}>
<Image
style={{
width: itemWidth,
height: 50,
}}
source={props.image}></Image>
</View>
</Animated.View>
</TouchableWithoutFeedback>
);
};
这是我从以下位置填充图像的地方:
图片.js:
export default class BottomImages extends Component {
state = {
columns: 3,
};
render() {
const { columns } = this.state;
return (
<View style={styles.container}>
<FlatList
numColumns={columns}
data={[
require('../resource/images/AzureDamsel.png'),
require('../resource/images/BicolourAngelfish.png'),
require('../resource/images/ClownTriggerfish.png'),
]}
renderItem={({ item }) => {
return (
<ListItem
itemWidth={(ITEM_WIDTH - 10 * columns) / columns}
image={item}
/>
);
}}
keyExtractor={(index) => {
return index;
}}
/>
</View>
);
}
}
如果需要,我还添加了一个沙箱供参考:沙箱代码
解决方案
您可以通过管理活动图像 ID 来实现这一点。
这里的基本思想是为每个图像添加一个唯一的 Id。并保留一个 Active Id 以跟踪当前点击了哪张图片。
state = {
columns: 3,
activeItemIndex: -1
};
平面列表应该看起来像 -
<FlatList
numColumns={columns}
data={[{
id: 1,
image: require('../resource/images/AzureDamsel.png')
},
{
id: 2,
image: require('../resource/images/BicolourAngelfish.png')
},
{
id: 3,
image: require('../resource/images/ClownTriggerfish.png')
}]}
renderItem={({ item }) => {
return (
<ListItem
itemWidth={(ITEM_WIDTH - 10 * columns) / columns}
image={item.image}
itemIndex={item.id}
activeItemIndex={activeItemIndex}
onChangeActiveItemIndex={(index)=>{
this.setState({
activeItemIndex: index
})
}}
/>
);
}}
keyExtractor={(index) => {
return index;
}}
/>
我修改了代码,这里更新了Link。代码并没有完全按照它应该的方式工作。但我希望你明白这一点。
推荐阅读
- javascript - querySelector 在单独的脚本文件中使用时返回 null
- qr-code - Google Charts API(QR 码)返回 HTTP 错误 502
- javascript - 如何将二维数组从 JavaScript 传递到 ejs 中的脚本标签?
- java - Java:如何根据提供的模式从字符串中提取值并将其填充到 Map?
- mysql - 从同一查询的多个组中选择一行
- asynchronous - 有没有办法在不调用另一个函数的情况下从成功处理程序中获取值?
- java - 测试程序错误
- docker - 关于 k8 空间中的 configmaps 和 secrets 的一般问题
- maven - 为什么不在 maven tomcat 中使用 / 作为上下文路径?
- php - 如何从 PHP 文件中包含数组并在另一个 PHP 文件中对其进行检查