不是最高的。
我试图使用剪接在某个位置删除文本方面。拼接数组时,它会如预期的那样出现。但是由于某种原因,最后的文本方面是被删除的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
值不受您的状态控制。
- 在
textarea
中设置sttributevalue
- 如果使用箭头功能,则不需要绑定
-
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>
);