我编写了一个由 TextInput、Button 和 FlatList 组成的 Android 应用程序。使用 TextInput 中写入的每个名称,平面列表中都会有一个项目。Item 标题将是 TextInput 内容,列表项旁边将有两个按钮和一个文本。一个按钮用于将 Text 显示的数字增加 1,另一个按钮用于减少。这是我的代码:
import React, {Component} from 'react';
import {
View,
Text,
TextInput,
FlatList,
TouchableOpacity,
} from 'react-native';
import { ListItem, SearchBar} from 'react-native-elements';
class App extends Component {
constructor(props) {
super(props);
this.state = {
task: "",
task_array: [],
};
}
ChangeText = (some_task) => {
this.setState({task: some_task});
};
pushAdd = () => {
let contact = {
name: this.state.task,
counter: 0,
};
this.setState({task_array: [...this.state.task_array, contact]});
};
renderListItem = ({item}) => {
return(
<View style={{flexDirection: 'row'}}>
<ListItem title={item.name} style={{width:'75%', marginLeft:20}}></ListItem>
<View style={{flexDirection:'row'}}>
<TouchableOpacity style={{ backgroundColor: 'blueviolet', height: 20, width: 20, borderRadius: 50}} onPress={()=> item={name:item.name, counter:item.counter + 1}}><Text>+</Text></TouchableOpacity>
<Text>{item.counter}</Text>
//main problem <TouchableOpacity style={{ backgroundColor: 'blueviolet', height: 20, width: 20, borderRadius: 50 }} onPress={() => item = { name: item.name, counter: item.counter - 1 }}><Text>-</Text></TouchableOpacity>
</View>
</View>
);
};
render() {
return(
<View style={{ backgroundColor: 'mediumturquoise', width:'100%', height:'100%'}}>
<FlatList
data = {this.state.task_array}
renderItem = {this.renderListItem}
keyExtractor = {(item) => item.name}>
</FlatList>
<View style = {{flexDirection : 'row', alignContent:'center', alignItems:'center'}}>
<TextInput onChangeText={this.ChangeText} style={{ backgroundColor: 'burlywood', height:50, width:'75%', borderRadius:30, marginBottom:20, marginLeft:20, marginRight:20}}></TextInput>
<TouchableOpacity style={{ backgroundColor: 'chocolate', height:40, width:50, borderRadius:10, marginBottom:20}} onPress={this.pushAdd}></TouchableOpacity>
</View>
</View>
);
}
};
export default App;
我用评论“主要问题”指出了有问题的行。增加和减少按钮不起作用,当我在应用程序中按下它们时,文本中的数字保持不变。我应该对我的增加和减少按钮的 onPress 方法执行什么更改以使它们工作?