例如,我有2个组成部分。当然,其中一个是父母,另一个是父母的孩子。我的目标是通过按钮删除组件,但是当我按下子组件内部的删除按钮时,功能是删除下一个组件。也许我forgot某物?
示例:[[1],[2],[3]]-嵌套数组与另一个数组。我想删除[2](parentArray [1])。但是删除删除[3](parentArray [2])的函数。那是我的麻烦。
父组件:
import React from 'react'
import classes from './Kanban.module.scss'
import Card from './Card/Card.js'
export default class Kanban extends React.Component {
constructor(props) {
super(props);
this.state = {
cards: [
]
}
this.createCardHandler = this.createCardHandler.bind(this);
this.deleteCardHandler = this.deleteCardHandler.bind(this);
}
createCardHandler() {
this.setState({
cards: this.state.cards.concat({ id: this.state.cards.length })
})
}
deleteCardHandler(index) {
this.setState(prevState => {
let cards = [...prevState.cards]
cards.splice(index, 1)
return {
cards: cards
}
})
}
render() {
let cards = null;
cards = this.state.cards.map((cards, id) => {
return (
<Card
index={cards.id}
id={cards.id}
onDelete={this.deleteCardHandler.bind(this, id)}
/>
)
})
return (
<>
<div>
<button className={classes.CreateCardButton} onClick={this.createCardHandler}>+</button>
{cards}
</div>
</>
)
}
}
子组件:
import React from 'react'
import classes from './Card.module.scss'
import List from './List/List.js'
export default class Card extends React.Component {
constructor(props) {
super(props);
this.state = {
lists: []
}
this.CreateListButton = this.CreateListButton.bind(this);
}
CreateListButton() {
this.setState({
lists: this.state.lists.concat('List')
})
}
deleteListHandler(index) {
let lists = [...this.state.lists]
lists.splice(index, 1)
this.setState({
lists
})
}
render() {
let lists = null
lists = this.state.lists.map((lists, index) => {
return (
<List
index={this.state.lists.length - 1}
onDelete={this.deleteListHandler.bind(this, index)}
/>
)
})
return (
<div className={classes.Card}>
<button className={classes.DeleteCardButton} onClick={this.props.onDelete}>✖</button>
<input maxLength='18' autoFocus className={classes.InputTitleInCard}></input>
{lists}
<button className={classes.CreateNewListButton} onClick={this.CreateListButton}>CREATE NEW LIST</button>
</div>
)
}
}
请在子组件中添加索引道具
cards = this.state.cards.map((card, index) => {
return (
<Card
index={card.id}
id={card.id}
//Here i giving child component function from parent component
onDelete={this.deleteCardHandler.bind(this, index)}
/>
)
})