我有一个组件,允许用户按下"添加"用于动态添加View组件的按钮。我已设法进行添加,但我如何改进代码以删除动态添加的视图组件?
import React, { Component } from 'react';
import {
View,
Text, Platform,
StyleSheet,
TouchableOpacity,
Animated,
ScrollView,
Image,
Button
} from 'react-native';
export default class App extends Component<{}>
{
constructor()
{
super();
this.state = { valueArray: [], disabled: false }
this.index = 0;
this.animatedValue = new Animated.Value(0);
}
addMore = () =>
{
this.animatedValue.setValue(0);
let newlyAddedValue = { index: this.index }
this.setState({ disabled: true, valueArray: [ ...this.state.valueArray, newlyAddedValue ] }, () =>
{
Animated.timing(
this.animatedValue,
{
toValue: 1,
duration: 500,
useNativeDriver: true
}
).start(() =>
{
this.index = this.index + 1;
this.setState({ disabled: false });
});
});
}
render()
{
const animationValue = this.animatedValue.interpolate(
{
inputRange: [ 0, 1 ],
outputRange: [ -59, 0 ]
});
let newArray = this.state.valueArray.map(( item, key ) =>
{
if(( key ) == this.index)
{
return(
<Animated.View key = { key } style = {[ styles.viewHolder, { opacity: this.animatedValue, transform: [{ translateY: animationValue }] }]}>
<Text style = {styles.text}>Row { item.index }</Text>
<Button style={styles.button}>
<Text style = {styles.text}>Remove</Text>
</Button>
</Animated.View>
);
}
else
{
return(
<View key = { key } style = { styles.viewHolder }>
<Text style = { styles.text }>Row { item.index }</Text>
<Button style={styles.button}>
<Text style = {styles.text}>Remove</Text>
</Button>
</View>
);
}
});
return(
<View style = { styles.container }>
<ScrollView contentContainerStyle = { this.scrollViewStyle }>
<View style = {{ flex: 1, padding: 4 }}>
{
newArray
}
</View>
</ScrollView>
<TouchableOpacity activeOpacity = { 0.8 } style = { styles.btn } disabled = { this.state.disabled } onPress = { this.addMore }>
<Image source = { require('./assets/add.png') } style = { styles.btnImage }/>
</TouchableOpacity>
</View>
);
}
}
答案 0 :(得分:0)
您只需要从this.state.valueArray中删除它。如果您知道要删除哪个索引,则可以将其作为;
removeItem = (index) => {
this.setState(prevState => ({
valueArray: prevState.valueArray.splice(index, 1),
}));
}
在这里,你基本上是一个索引,从前一个创建一个没有所述索引的新数组并更新状态。