首页 > 解决方案 > 尝试在本机反应中动态创建文本输入

问题描述

我正在创建一个 Todo 应用程序来练习我所学的内容。当用户按下按钮时,我尝试动态创建文本输入。但是,我已经被困了一段时间,无法弄清楚。这是我的代码。任何帮助深表感谢。我的主要问题是用户输入的句柄与文本输入的创建以及如何处理它。

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>
  )
  }
 }

标签: react-native

解决方案


推荐阅读