React native 无法在flatlist renderItem中使用删除功能
删除功能在flatlist renderItem方法中不起作用,但如果我使用map函数而不是flatlsit来渲染数据,它将非常好地工作 下面是示例代码React native 无法在flatlist renderItem中使用删除功能,react-native,react-native-flatlist,setstate,React Native,React Native Flatlist,Setstate,删除功能在flatlist renderItem方法中不起作用,但如果我使用map函数而不是flatlsit来渲染数据,它将非常好地工作 下面是示例代码 class App extends Component { state = { todos: [ { todo: 'go to gym', id: 1 }, { todo: 'buy a mouse', id: 2 }, { todo: 'practice hash table', id: 3 }
class App extends Component {
state = {
todos: [
{ todo: 'go to gym', id: 1 },
{ todo: 'buy a mouse', id: 2 },
{ todo: 'practice hash table', id: 3 },
{ todo: 'iron clothes', id: 4 }
]
};
keyExtractor = item => item.id.toString();
handleDelete = id => {
const todos = this.state.todos.filter(item => item.id !== id);
this.setState({ todos });
};
renderItems({ item }) {
return (
<View
style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between'
}}
>
<Text style={{ fontSize: 16 }}>{item.todo}</Text>
<TouchableOpacity
onPress={() => this.handleDelete(item.id)}
style={{ marginRight: 15 }}
>
<Text style={{ color: 'red' }}>Delete</Text>
</TouchableOpacity>
</View>
);
}
render() {
return (
<View>
{/* {this.renderItems()} */}
<FlatList
data={this.state.todos}
keyExtractor={this.keyExtractor}
renderItem={this.renderItems}
/>
</View>
);
}
}
类应用程序扩展组件{
状态={
待办事项:[
{todo:'去健身房',id:1},
{todo:'买只老鼠',id:2},
{todo:'练习哈希表',id:3},
{todo:'铁衣服',id:4}
]
};
keyExtractor=item=>item.id.toString();
handleDelete=id=>{
const todos=this.state.todos.filter(item=>item.id!==id);
this.setState({todos});
};
renderItems({item}){
返回(
{item.todo}
this.handleDelete(item.id)}
style={{marginRight:15}
>
删除
);
}
render(){
返回(
{/*{this.renderItems()}*/}
);
}
}
我无法理解它给我错误的原因_this2.handleDelete不是函数。您没有绑定函数,在构造函数中绑定函数或使用数组函数
renderItems = ({ item }) => {
return (
<View
style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
}}>
<Text style={{ fontSize: 16 }}>{item.todo}</Text>
<TouchableOpacity
onPress={() => this.handleDelete(item.id)}
style={{ marginRight: 15 }}>
<Text style={{ color: 'red' }}>Delete</Text>
</TouchableOpacity>
</View>
);
}
renderItems=({item})=>{
返回(
{item.todo}
this.handleDelete(item.id)}
样式={{marginRight:15}}>
删除
);
}
Ya。。。谢谢,它可以工作,但我不明白为什么我需要绑定renderItems?当我已经绑定handleDeleteYa。。。谢谢,它可以工作,但我不明白为什么我需要绑定renderItems?当我已经绑定handleDelete时,这个在renderItems
中引用了一个不同的东西,你需要绑定它来为它提供类上下文。你也将这个绑定到handleDelete
但是你不是在HandleDeletes
中调用这个而是在renderItems
中调用JUnitUsl。我想你需要说三遍,也许PO会考虑接受你的答案。