我已经编写了一个Android应用程序,它由TextInput,Button和FlatList组成。使用在TextInput中写入的每个名称,在平面列表中将有一个项目。Item标题将是TextInput内容,并且在列表项旁边将有两个按钮和一个文本。一个按钮用于将“文本”显示的数字增加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方法执行什么更改才能使它们起作用?
在React中,您不能直接操作数据(就像在onPress方法中的+/-按钮中一样)。这将无效,相反,您需要使用setState
最快的解决办法是改变
// this
renderListItem = ({item}) => {
// to this
renderListItem = ({item, index}) => {
知道渲染项目的索引。然后,更改onPress
这些项目中您的递增/递减按钮的方法以setState
代替
// from this
onPress={()=> item={name:item.name, counter:item.counter + 1}}
// to this
onPress={() =>
this.setState({
task_array: this.state.task_array
.map((item, itemIndex) =>
itemIndex !== index
? item
: {
...item,
counter: item.counter + 1
})
})}
这里发生的是,我们使用array的.map()方法从旧的数组中创建了一个新的task_array,除了单击的一个元素(我们通过比较索引定义)之外,其他所有元素都保持不变。在这种情况下,我们增加它的计数器,并通过使用将新值分配给task_arraythis.setState
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句