如何删除正确的文本区域?

How can I delete the correct textarea?

我正在尝试使用拼接删除某个位置的文本区域。拼接数组的时候,果然出来了。但是由于某些原因,最后的textarea是被删除的textarea,而不是我要删除的textarea。

我已经尝试过使用 2 个不同的数组,但结果相同。我不确定还能尝试什么。

class App extends Component {

  state = {
    pro : []
  }

  //onclick add a textarea
  onclick = () => {

    let arr = this.state.pro;

    arr = this.state.pro.concat(0);

    this.setState(
      {
        pro : arr
      }
    )

    console.log(arr);
  }

  //change the text content of a textarea at an index

  onchange = (i, e) => {
    let arr = this.state.pro;

    arr[i] = e.target.value;

    this.setState(
      {
        pro : arr
      }
    )
  }

  remove = (i, e) => {
    let arr = this.state.pro
     arr.splice(i, 1)

     this.setState(
      {
          pro: arr
      })
  }

  render() {

    console.log(this.state.pro)

    return (
      <div>

        {this.state.pro.map((con, k) => 
            <div key = {k}>
              <textarea key = {k} onChange = {this.onchange.bind(this, k)}></textarea>
              <button onClick = {this.remove.bind(this, k)}>-</button>
            </div>
        )}

        <button onClick = {this.onclick}>+</button>
      </div>
    );
  }
}

没有错误消息。预期的结果是,当我按下旁边的减号按钮时,正确的文本区域将被删除。每次都不顶

因为你的textarea值不受国家控制。

  • textarea
  • 中设置属性 value
  • 如果使用箭头函数则不需要绑定
  • key 不需要 textarea
return (
            <div>

                {this.state.pro.map((con, k) =>
                    <div key = {k}>
                        <textarea value={con} onChange = {(e) => this.onchange(k, e)}/>
                        <button onClick = {(e) => this.remove(k, e)}>-</button>
                    </div>
                )}

                <button onClick = {this.onclick}>+</button>
            </div>
        );