简体   繁体   English

如何在本机反应中添加动态输入?

[英]How to add dynamic inputs in react native?

I have 3 inputs and plus button when pressed it I want to add another 3 inputs so with his state,我有 3 个输入和加号按钮,按下它我想再添加 3 个输入,所以他的状态,

the state like this这样的状态

state={
 toolsUsed: [
      {
        id: (Math.random() * 150).toString(),
        name: '',
        price: '',
        count: '',
      },
     {..},
    ],
}

in the first 3 input component, I want when I add a change value text set the state with this value!在前 3 个输入组件中,我想在添加更改值文本时使用此值设置状态!

but I tried it but after changing the text I got in a state但我试过了,但在更改文本后,我处于一种状态

toolsUsed => [" ","text"]

what I want to achieve我想要达到的目标

toolsUsed => [{name:'text",count:'..',price:'....',id:'..'},{...}]

UI用户界面

用户界面

here's my code这是我的代码

renderToolsUsed = () => {
   const {toolsUsed} = this.state;
   const prom = toolsUsed.map(({name, id, price, count}, i) => {
      return (
        <View>
          <View style={styles.toolsItem}>
            <TextInput
              onChangeText={name =>
                this.setState(
                  prevState => {
                    return {
                      ...prevState,
                      toolsUsed: [prevState.toolsUsed[i].name, name],
                    };
                  },
                  () => console.log(this.state.toolsUsed),
                )
              }
              value={name}
              key={id}
            />
          </View>


          <View style={styles.toolsItem}>
            <TextInput
              onChangeText={count => this.setState({})}
              value={count}
              key={id}
            />
          </View>

          <View style={styles.toolsItem}>
            <TextInput
              onChangeText={price => this.setState({})}
              value={price}
              key={id}
            />
          </View>
          <TouchableOpacity onPress={() =>
          this.setState(prevState => {
            return {
              ...prevState,
              toolsUsed: prevState.toolsUsed.length + 1,
            };
          })
        }> **// heres i got error "toolsUsed.map not a function**
            <Text>+</Text>
          </TouchableOpacity>
        </View>
      );
    });

     return prom;
   }

JSX JSX

...
render(){
  return(
      <View style={styles.toolsContainer}>
            <Text>
              Tools
            </Text>
            {this.renderToolsUsed()}
        </View>
     );
 }

EDIT~1编辑~1

maybe :D solve plus function也许:D解决加功能

 onPress={() => {
                let newInput = this.state.toolsUsed.length;
                this.setState(prevState => ({
                  toolsUsed: prevState.toolsUsed.concat([newInput]),
                }));
         } 

EDIT ~ 2编辑 ~ 2

I add a minus button to delete the last object in tools array, here two ways to handle it, but I have something weird on the first way it's work well I don't know why!我添加了一个减号按钮来删除工具数组中的最后一个对象,这里有两种处理它的方法,但我在第一种方法上有一些奇怪的东西,它运行良好,我不知道为什么! but when I comment first var newInput it's don't delete the last item但是当我第一次评论 var newInput它不会删除最后一项

onPress={() => {
        // first way
         let newInput = this.state.toolsUsed.pop();
         this.setState(prevState => ({
              toolsUsed: prevState.toolsUsed.filter(
                 tool => tool.id !== id,
               ),
         }));
       // Second
         let rowDeleted = [...this.state.toolsUsed];
         rowDeleted.splice(-1, 1);
         this.setState({toolsUsed: rowDeleted});
 }}

You have to do something like this in the state update.你必须在状态更新中做这样的事情。 It's not pretty, but your edit of the state is pretty deep.它不漂亮,但是您对状态的编辑非常深入。

This should edit the name of the i'th element in the toolsUsed property of your state:这应该编辑您所在州的 toolsUsed 属性中第 i 个元素的名称:

onChangeText = {name =>
    this.setState(
        prevState => {
            return {
                toolsUsed: [
                    ...prevState.toolsUsed.slice(0, i),
                    {
                        ...prevState.toolsUsed[i],
                        name
                    },
                    ...prevState.toolsUsed.slice(i + 1)
                ],
            };
        },
        () => console.log(this.state.toolsUsed),
    )
}

Note that your TouchableOpacity onPress also breaks your state.请注意,您的TouchableOpacity onPress也会破坏您的状态。 It replaces the array with a number.它用数字替换数组。

Your edited function still doesn't add a correct new entry to the array.您编辑的函数仍然没有向数组添加正确的新条目。 It should add an object with the same structure.它应该添加一个具有相同结构的对象。 It should look something like this:它应该是这样的:

onPress={() => {
    let newInput = {id: generateId(), name: '', price: '', count: '',};
    this.setState(prevState => ({
        toolsUsed: [...prevState.toolsUsed, newInput],
    }));
}}

As you mentioned in the comments, the last fix missing was adding stable keys to each View in the mapped array, like this: <View key={i} >..</View>正如您在评论中提到的,缺少的最后一个修复是为映射数组中的每个视图添加稳定键,如下所示: <View key={i} >..</View>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM