React 原生文本输入"Each child in a list should have a unique "关键" prop."



当我在Expo项目中运行此代码时,我得到以下错误:

警告:列表中的每个子项都应该有一个唯一的";键";道具检查AddParticipant的渲染方法。有人能帮我一下吗?

import React, { Component } from 'react';
import { View, TextInput, Button, StyleSheet } from 'react-native';

class AddParticipant extends Component {
constructor(props){
super(props);
this.state = {
textInput : [],
inputData : []
}
}
//function to add TextInput dynamically
addTextInput = (index) => {
var name_id = " First Name & Last Name" + " " +(index +1 );
let textInput = this.state.textInput;
textInput.push(<TextInput  style={styles.textInput} placeholder={name_id}
onChangeText={(text) => this.addValues(text, index)} />
);      
this.setState({ textInput });
}
//function to remove TextInput dynamically
removeTextInput = () => {
let textInput = this.state.textInput;
let inputData = this.state.inputData;
textInput.pop();
inputData.pop();
this.setState({ textInput,inputData });
}
//function to add text from TextInputs into single array
addValues = (text, index) => {
let dataArray = this.state.inputData;
let checkBool = false;
if (dataArray.length !== 0){
dataArray.forEach(element => {
if (element.index === index ){
element.text = text;
checkBool = true;
}
});
}
if (checkBool){
this.setState({
inputData: dataArray
});
}
else {
dataArray.push({'text':text,'index':index});
this.setState({
inputData: dataArray
});
}
}
//function to console the output
getValues = () => {
console.log('Data',this.state.inputData);
}

render(){
return(
<View>
<View style= {styles.row}>
<View style={{margin: 10}}>
<Button title='Add Participant' onPress={() => this.addTextInput(this.state.textInput.length)} />
</View>
<View style={{margin: 10}}>
<Button title='Remove Participant' onPress={() => this.removeTextInput()} />
</View>
</View>
{this.state.textInput.map((value) => {
return value
})}
<Button title='Save The Participants' onPress={() => this.getValues()} />
</View>

)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
},
buttonView: {
flexDirection: 'row'
},
textInput: {
height: 40,
borderColor: 'black', 
borderWidth: 1,
margin: 20
},
row:{
flexDirection: 'row',
justifyContent: 'center'
},
});
export default AddParticipant;

您返回的必须有一些关联的键。即,您必须为每个组件提供一个密钥。

以下是你能做的,

addTextInput = (index) => {
var name_id = " First Name & Last Name" + " " +(index +1 );
var key = index; // add this statement in the code. It'll remove the warning 
let textInput = this.state.textInput;
textInput.push(<TextInput key={key} style={styles.textInput} placeholder={name_id}
onChangeText={(text) => this.addValues(text, index)} />
);      
this.setState({ textInput });
}

相关内容

最新更新