【问题标题】:how to handle multiple textInput states created dynamically in React Native如何处理在 React Native 中动态创建的多个 textInput 状态
【发布时间】:2019-03-01 20:10:43
【问题描述】:

我们如何从动态创建的文本输入中访问值。像平面列表一样创建 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>
 );
};

【问题讨论】:

    标签: reactjs react-native react-native-android react-native-ios react-native-flatlist


    【解决方案1】:

    您可以将输入的文本存储在您的状态中。只听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})}
    

    【讨论】:

    • 感谢您,此解决方案有效。如何处理选择器(下拉)及其选定的状态数组。
    • 基本上是一样的——在某些事件(onChange、onPress 等)上附加一个函数来更新你的状态。不要忘记制作数据的副本,您将进行更新。
    • 我已经尝试了 onValueChange 方法,通过提供函数来改变所选选择器的状态,请您提供示例示例
    • 我已经尝试了给定的解决方案,但仍然无法正常工作。你会帮助我哪里错了吗? link
    • 86 行:newArray[value] = index; -> 将其更改为 newArray[index] = value; 并且:在 onValueChange 函数中交换参数 -> onValueChange(index: number, value: string)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2020-11-15
    • 2021-11-23
    • 2021-06-15
    • 2019-08-12
    • 1970-01-01
    相关资源
    最近更新 更多