如何处理在 React Native 中动态创建的多个 textInput 状态

how to handle multiple textInput states created dynamically in React Native

我们如何从动态创建的文本输入中访问值。就像平面列表创建 3 个文本输入,然后在单击按钮时我们验证添加了哪一个,没有添加哪一个。如何管理多个状态数组。目前我这样做了

const data = [1,2];

constructor(props) {
super(props);
this.state = {
  Textdata:[],
};

}

  SubmitButton(){
//how to access those text input values and add to array
}


<FlatList
data={data}
renderItem={this.renderItem}
keyExtractor={(item, index) => item}
 />

renderItem = ({ item, index }) => {

return (
    <View>
     <Item 
        floatingLabel 
        style={styles.InputBoxStyle}
        >
        <Label>First Name</Label>
        <Input 

          />
     </Item>
     <Item 
        floatingLabel 
         style={styles.InputBoxStyle}>
         <Label>Last Name</Label>
        <Input 

          />
      </Item>
<Button rounded
        onPress={this.SubmitButton}>
        <Text>Submit</Text>
     </Button>

    </View>
 );
};

您可以将输入文本存储在您的状态中。只需监听 onChangeText 事件。尝试将此添加到您的输入中:

onChangeText={val => updateState(index, val) />

其中 index 是您的项目在 renderItem 函数中的索引。后期添加方法:

updateState = (index,value) => {
   const Textdata = [...this.state.Textdata]; //make a copy of array
   Textdata[index] = value;
   this.setState({ Textdata: Textdata });
}

然后按下按钮就可以验证这个数组了。

再举个例子,当Picker组件的值发生变化时,你可以这样处理:

onValueChange={itemValue => this.setState({someNameForThisPicker: itemValue})}