尝试动态创建Textinput in react native

时间:2018-05-16 21:41:38

标签: react-native

我正在创建一个Todo应用程序来练习我学到的东西。当用户按下按钮时,我试图动态创建textinput。但是,我已经被困了一段时间而且还没能弄清楚。这是我的代码。任何帮助深表感谢。我的主要问题是用户输入的句柄,创建textinput以及如何处理它。

import React from 'react';
import {StyleSheet, View, Button, TextInput, ScrollView} from 'react-                    
native';
import {Constants} from 'expo';
import FormNewTodo from '../components/FormNewTodo'


const styles = StyleSheet.create ({
appContainer: {
 flex: 1,
 paddingTop: Constants.statusBarHeight,
 backgroundColor: 'white',
 },
 form: {
 padding: 10,
 borderColor: 'black',
 borderWidth: 1,
 },
})

let id = 0


export default class AddTodoForm extends React.Component {
  state = {
   titleText: '',
   formItems: [],
   }


  handleAddTodo = () => {
    this.setState({
      formItems: [...this.state.formItems, {id: id++, text: ''},],
     })
     };

  handleformItemsChange = text => {
 // pass the formItems state to a variable       
 let newArray = [...this.state.formItems];
 let item = [];

  /*Check if it´s the beginning of a new input or to check if the 
  user is going to an old input to edit it*/
  if (text.length === 1) 
  {
  item = newArray.filter(item => item.text === '')}
   else {
   item = newArray.filter(item => item.text === text[text.length - 1])}

  //pass the item to the right element in the array and the update 
   state
 let index = item[0].id;
 item[0].text = text;
 newArray[index] = item;
 this.setState({ formsItems: newArray });
 }



 handleFormTitleChange = titleText => {
  this.setState({titleText: titleText})
  }


  handleSave = () => {
   this.props.onSubmit(this.state)
   let id = 0
   };

  static navigationOptions = ({ navigation }) => {
      return {
       headerTitle: 'TO DO´s',
       headerRight: (
         <Button
           title="Add"
           onPress={() => navigation.navigate('AddTodoForm')}
          />
         ),
        };
       };


 render() {
   return (
    <View>
      <View>
       <TextInput style={styles.form} 
                value={this.state.titleText}
                onChangeText={this.handleFormTitleChange}
                placeholder={'Title'}/>
    </View>
    <ScrollView>
    {this.state.formItems.map(item => <FormNewTodo 
                key={item.id}
                onChangeText={this.handleformItemsChange}
                value={item.text}
                />)}
    </ScrollView>
    <Button onPress={this.handleSave} title='Save'/>
    <Button onPress={this.handleAddTodo} title='Add Todo'/>
 </View>
  )
  }
 }

0 个答案:

没有答案