我在 React Native 应用程序中有以下视图:
这是它的代码:index.js
import React, {useContext} from 'react';
import {View, StyleSheet} from 'react-native';
import {Headline, Button, IconButton} from 'react-native-paper';
import ShoppingCartEntry from './ShoppingCartEntry';
import ShoppingCartContext from '../../context/shoppingCart/shoppingCartContext';
const ShoppingCartList = () => {
const {shoppingCart} = useContext(ShoppingCartContext);
const TotalPriceDisplay = () => {
let totalPrice = 0;
shoppingCart.map((entry) => {
totalPrice = totalPrice + (entry.product.price * entry.amount);
})
return (
<Headline>Total: {totalPrice}</Headline>
)
}
return (
<View style={styles.cartContainer}>
<View style={styles.icon}>
<IconButton icon='cart' color='black' size={40}/>
</View>
{shoppingCart.map((entry) => {
return (
<ShoppingCartEntry entry={entry} />
)
})}
<View style={styles.totalPrice}>
<TotalPriceDisplay />
<Button mode='contained'>
Comprar
</Button>
</View>
</View>
)
}
styles = StyleSheet.create({
cartContainer: {
flexDirection: 'column',
},
totalPrice: {
alignItems: 'center'
},
icon: {
alignItems: 'center'
}
})
export default ShoppingCartList;
ShoppingCartEntry.js
import React, {useContext} from 'react';
import {View, StyleSheet} from 'react-native';
import {Headline, IconButton, Text} from 'react-native-paper';
import ShoppingCartContext from '../../context/shoppingCart/shoppingCartContext';
const ShoppingCartEntry = ({entry}) => {
const {shoppingCartAppendProduct, shoppingCartUpdateProduct, shoppingCartRemoveProduct} = useContext(ShoppingCartContext);
const removeProduct = () => {
shoppingCartRemoveProduct(entry.product.id);
}
const Counter = () => {
return (
<View style={styles.counterContainer}>
<View style={styles.counter}>
<IconButton icon='plus' color='black' onPress={removeProduct} />
</View>
<View>
<Headline color='blue'>{entry.amount}</Headline>
</View>
<View style={styles.counter}>
<IconButton icon='minus' color='black' onPress={removeProduct} />
</View>
</View>
)
}
return (
<View style={styles.entryContainer}>
<View style={styles.button}>
<IconButton icon='delete' color='red' onPress={removeProduct} />
</View>
<View style={styles.name}>
<Headline>{entry.product.name}</Headline>
<Text>{entry.product.price}</Text>
</View>
<View style={styles.amount}>
<Counter />
<Text style={{textAlign: 'right'}}>{entry.product.price * entry.amount}</Text>
</View>
</View>
)
}
styles = StyleSheet.create({
entryContainer: {
flexDirection: 'row',
paddingBottom: 20,
paddingLeft: 20
},
name: {
flex: 0.5
},
amount: {
flex: 0.3
},
button: {
alignItems: 'flex-end',
flex: 0.1
},
counterContainer: {
flexDirection: 'row'
},
counter: {
alignItems: 'flex-end',
justifyContent: 'center',
flexDirection: 'row'
}
})
export default ShoppingCartEntry;
问题是当一个元素被移除shoppingCart
并重新渲染整个视图时,它会失去所有的格式:
我发现我所要做的就是StyleSheet.flexDirection
将容器的 更改为row
,column
然后再更改回row
,视图再次排列,但现在使用新数据。
我不知道这是否是我不应该关心生产的开发阶段问题,或者我是否可以采取一些措施来避免它。