React Native ошибка при нахождении ключа
ReferenceError: key is not defined
Main.deleteNote
C:/ReactNative/First/NewTodo/components/Main.js:70
67 | }
68 |
69 | deleteNote(){
> 70 | this.state.noteArray.splice(key, 1);
71 | this.setState({noteArray: this.state.noteArray});
72 | }
73 | }
View compiled
deleteMethod
C:/ReactNative/First/NewTodo/components/Main.js:20
17 |
18 | let notes = this.state.noteArray.map((val, key) => {
19 | return <Note key={key} keyval={key} val={val}
> 20 | deleteMethod={ () => this.deleteNote(key)} />
| ^ 21 | });
22 |
23 | return (
Код
Main.js
import React from 'react';
import { StyleSheet, Text, View, TextInput, ScrollView, TouchableOpacity, KeyboardAvoidingView } from 'react-native';
import Note from './Note';
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
noteArray:[],
noteText:"",
};
}
render(){
let notes = this.state.noteArray.map((val, key) => {
return <Note key={key} keyval={key} val={val}
deleteMethod={ () => this.deleteNote(key)} />
});
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Заметки</Text>
</View>
<ScrollView style={styles.scrollContainer}>
{notes}
</ScrollView>
<KeyboardAvoidingView style={styles.footer} behavior="padding">
<TextInput
onChangeText={(noteText) => this.setState({noteText})}
value={this.state.noteText}
style={styles.textInput}
placeholder='Введите заметку..'
placeholderTextColor='#fff'
underlineColorAndroid='transparent'
>
</TextInput>
<TouchableOpacity style={styles.addButton} onPress={this.addNote.bind(this)}>
<Text style={styles.addButtonText}>+</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</View>
);
}
addNote(){
if(this.state.noteText){
let d = new Date();
this.state.noteArray.push({
'date':d.getFullYear() + ":" + d.getMonth() + ":" + d.getDate(),
'note': this.state.noteText
});
this.setState({noteArray: this.state.noteArray});
this.setState({noteText:''});
}
}
deleteNote(){
this.state.noteArray.splice(key, 1);
this.setState({noteArray: this.state.noteArray});
}
}
Note.js
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
export default class Note extends React.Component {
render(){
return (
<View key={this.props.keyval} style={styles.note}>
<Text style={styles.noteText}>{this.props.val.note}</Text>
<Text style={styles.noteText}>{this.props.val.date}</Text>
<TouchableOpacity onPress={this.props.deleteMethod}style={styles.noteDelete}>
<Text style={styles.noteDeleteText}>+</Text>
</TouchableOpacity>
</View>
);
}
}