【发布时间】:2021-06-14 20:09:39
【问题描述】:
所以我正在尝试构建一个动态文本字段,一切正常,但我在从状态/数组中删除数据时遇到问题。 splice 总是删除最后一个索引而不是自定义索引。这是我的整个代码。顺便说一句,我正在使用 reactjs 作为前端框架。
import React from 'react'
class Form extends React.Component {
constructor(props){
super(props)
this.state = {
firstName: "",
lastName: "",
books: []
}
this.onSubmitHandle = this.onSubmitHandle.bind(this)
this.onChangeHandle = this.onChangeHandle.bind(this)
}
onSubmitHandle = (event) => {
event.preventDefault()
console.log(this.state)
}
onChangeHandle = (event) => {
event.preventDefault()
if(["book"].includes(event.target.name)) {
let books = [...this.state.books]
books[event.target.dataset.id][event.target.name] = event.target.value
} else {
this.setState({
[event.target.name]: event.target.value
})
}
}
addNewRow = () => {
this.setState((prevState) => ({
books: [...prevState.books, { "book": "" }]
}))
}
removeRow = (index) => {
const newBooks = [...this.state.books];
newBooks.splice(index, 1)
this.setState({books: newBooks})
}
render() {
return(
<div>
<form onSubmit={this.onSubmitHandle}>
<input type="text" name="firstName" onChange={this.onChangeHandle} placeholder="First Name" />
<input type="text" name="lastName" onChange={this.onChangeHandle} placeholder="Last Name" />
<br></br>
{
this.state.books.map((val, i) => {
return(
<div key={i}>
<input type="text" data-id={i} onChange={this.onChangeHandle} name="book" placeholder={i} />
<button type="button" onClick={this.removeRow.bind(this, i)}>Remove {i}</button>
</div>
)
})
}
<br></br>
<button type="button" onClick={this.addNewRow.bind(this)}>Add</button>
<br></br>
<button type="submit">Submit</button>
</form>
</div>
)
}
}
export default Form
【问题讨论】:
标签: javascript arrays reactjs splice array-splice