【发布时间】:2020-11-15 11:34:50
【问题描述】:
我正在尝试创建动态 TextInput,然后通过循环索引将 TextInput 的值保存到另一个状态,但我没有得到所需的输出。
我认为问题出在循环中,因为onChangeText 的console.log 对于i 的值始终是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
},
});
【问题讨论】:
标签: reactjs react-native state textinput