Append TextInput component one after another when press button in React Native

前端 未结 1 445
猫巷女王i
猫巷女王i 2021-01-06 18:47

I am new in React Native.

I am using two button to add TextInput component in the view. When I press Add button, it pushes on

相关标签:
1条回答
  • 2021-01-06 19:23

    The problem is that you are calling insertSomeThing function and this function push a new <Text> in variable arr and then it is rendered in the following order:

    </View>
        { arr }
        {arrAnother}
    </View>
    

    If you want to insert a different TextView at the end of the list you must remove {arrAnother} and modify your map functions. Your code will look like this:

    insertSomeThing( placeholder ){
      this.state.arr.push({index:index++, placeholder:placeholder});
      this.setState({ arr: this.state.arr });
    }
    
    render() {
      let arr = this.state.arr.map((r, i) => {
        return (
          <View key={ i } style={styles.insertStyle}>
            <TextInput placeholder = {r.placeholder} />
          </View>
        );
      });
    
      return (
        <View style={styles.container}>
          <View>
            <TouchableHighlight 
              onPress={ () => this.insertSomeThing('add') } 
              style={styles.button}>
    
              <Text>Add</Text>
            </TouchableHighlight>
          </View>
          <View>
            <TouchableHighlight 
              onPress={ () => this.insertSomeThing('addAgain') } 
              style={styles.button}>
                 <Text>Add Again</Text>
            </TouchableHighlight>
          </View>
          { arr }
        </View>
      );
    }
    

    EDIT

    To handle onChangeText your TextInput will look like this:

    let arr = this.state.arr.map((r, i) => {
    
        var ref = 'textinput'+i;
    
        return (
          <View key={ i } style={styles.insertStyle}>
            <TextInput ref={ref} onChangeText={(text) => this._onChangeText(text,ref)} />
          </View>
        );
      });
    

    You have to define _onChangeText in your component to handle the event. You will receive text and reference to the input. You later can reference the input using this.refs[ref].

    0 讨论(0)
提交回复
热议问题