我试图创建动态TextInput,然后通过循环索引将TextInput的值保存到另一种状态,但我没有得到所需的输出。
我认为问题出在循环中,因为i
值的onChangeText
的console.log总是TextInputs的数量。
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View,TextInput, FlatList, Button, } from 'react-native';
export default function App() {
const [value,setValue]=useState(1)
const[textInput,setTextInput]=useState([])
const[inputData,setInputData]=useState([{index:0,text:''},{index:1,text:''},{index:2,text:''}])
useEffect(()=>{
addTextInput()
},[value])
const addTextInput=()=>{
var Input=[];
for(var i=0;i<value;i++){
Input.push(
<TextInput style={styles.textInput}
onChangeText={(text)=>{
var newarray = [...inputData]
var index = newarray.findIndex((dd) =>dd.index==i)
console.log('index',index,'i',i); //------>idk why but the value of i is always the no of text
// input pls hwlp me with
// these loop.i think i have done something wrong in here
newarray[index] = {index:i,text:text}
setInputData(newarray)} }
/>)
}
setTextInput(Input);
}
return (
<View style={styles.container}>
<View style={{height:50,color:'green',backgroundColor:'green',marginBottom:20}}/>
<View style={{flexDirection:'row',justifyContent:'space-around'}}>
<Text style={{fontSize:20,alignSelf:'center'}}>No Of Tenents:</Text>
</View>
<View style={{flexDirection:'row',justifyContent:'space-around'}}>
<Button title='1' onPress={()=>setValue(1)}/>
<Button title='2' onPress={()=>setValue(2)}/>
<Button title='3' onPress={()=>setValue(3)} />
</View>
<FlatList data={textInput}
renderItem={({item})=>{
return item
}}/>
</View>
);
}
const pickerSelectStyles = StyleSheet.create({
inputIOS: {
fontSize: 16,
paddingVertical: 12,
paddingHorizontal: 10,
borderWidth: 1,
borderColor: 'gray',
borderRadius: 4,
color: 'black',
paddingRight: 30,
},
inputAndroid: {
fontSize: 16,
paddingHorizontal: 10,
paddingVertical: 8,
borderWidth: 1,
borderColor: 'green',
borderRadius: 8,
color: 'black',
paddingRight: 50,
},
});
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
textInput: {
height: 40,
borderColor: 'black',
borderWidth: 1,
margin: 20
},
});
在循环中使用let来声明i,因为let只能在声明的范围内可用。[阅读此]
如果你想删除循环,
const addTextInput = () => {
var Input = [...textInput];
if (Input.length < value) {
const InputIndex = Input.length;
Input.push(
<TextInput
style={styles.textInput}
onChangeText={text => {
var newarray = [...inputData];
const index = newarray.findIndex(dd => dd.index === InputIndex);
newarray[index] = {index: index, text: text};
setInputData(newarray);
console.log(newarray);
}}
/>,
);
} else {
Input.pop();
}
setTextInput(Input);
};
使用let
而不是var
解决了我的问题。