Add Inputs in React with add button

前端 未结 3 895
花落未央
花落未央 2021-01-25 23:20

I\'m trying to make a set of inputs that can be duplicated or removed.

I\'ve found and used a combination of this : https://jsfiddle.net/69z2wepo/36745/ and this (becaus

相关标签:
3条回答
  • 2021-01-25 23:39

    Remove const count and initialize a count variable in state.

    constructor(props) {
            super(props);
            this.state = { inputList: [], count: 0 };
            this.incrementCount = this.incrementCount.bind(this);
            this.decrementCount = this.decrementCount.bind(this);
        }
    

    Then use this.state.count as key in input element:

    incrementCount() {
          const inputList = this.state.inputList;
            this.setState({
                count: this.state.count + 1,
                inputList: inputList.concat(<Input key={this.state.count} />),
            });
        }
        decrementCount() {
          const inputList = this.state.inputList;
            this.setState({
                count: this.state.count - 1,
                inputList: inputList.concat(<Input key={this.state.count} />),
            });
        }
    
    0 讨论(0)
  • 2021-01-25 23:44

    The key that is passed in <Input key={count} /> should be unique. You shouldn't have two items in the list with the same key value.

    In your case, when you do 2 subsequent increment and decrement, you end up with same count value. That means same key repeated for different <Input/> tag

    console.log the count to check if its unique. The key 0 is used twice in the array, that's what the error means.

    0 讨论(0)
  • 2021-01-25 23:47

    add count in the initial state.

    this.state = { inputList: [] , count :0}; 
    

    Then remove this line const count = 0;

    Since you're using count as your key change this also to.

    <Input key={this.state.count} />

    I made a jssfiddle for another question, the concept is similar so it might be helpful.

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