如何从React.js中的数组中删除JSX元素?

时间:2019-10-11 13:11:07

标签: javascript html css reactjs

我有一个状态数组,其中包含一些JSX元素列表。我试图在单击按钮时从数组中删除一个特定元素,即JSX,但是我不知道该怎么做。任何帮助将不胜感激。

Section.js

class Section extends React.Component {
    state = {
        sections: []
    };

    addLectureHandler = () => {
        const secs = this.state.sections;
        secs.push(
            <LectureItem key={Math.random} removeLectureHandler={() => this.removeLectureHandler(<LectureItem />)} />
        );
        this.setState({ sections: secs });
    };

    removeLectureHandler = (item) => {
        console.log(item);
    };

    render() {
        const { classes } = this.props;
        return (
            <div className={classes.container}>
                <h4 className={classes.sectionTitle}>
                    Section 1 - <AssignmentIcon /> Introduction
                </h4>
                <div className={classes.addButtonContainer}>
                    <Button variant="outlined" className={classes.addButton} onClick={this.addLectureHandler}>
                        Create Lecture
                    </Button>
                </div>
                <div className={classes.lectureContainer}>{this.state.sections}</div>
            </div>
        );
    }
}

export default withStyles(styles)(Section);

LectureItem.js

class LectureItem extends React.Component {
    render() {
        const { classes, removeLectureHandler } = this.props;
        return (
            <div className={classes.container}>
                <div className={classes.titleContainer}>
                    <TextField className={classes.textField} label="New Lecture Title" name="lecture" margin="normal" />
                    <Button className={classes.removeButton} onClick={removeLectureHandler}>
                        <ClearIcon />
                    </Button>
                </div>
                <Button variant="contained" color="primary" className={classes.button}>
                    Add
                </Button>
            </div>
        );
    }
}

export default withStyles(styles)(LectureItem);

1 个答案:

答案 0 :(得分:1)

它非常直接,它更多的是逻辑语句而不是反应,让我向您展示

为您服务的方法addLectureHandler 将push命令更改为以下

 secs.push(
        <LectureItem key={Math.random} removeLectureHandler={() => this.removeLectureHandler(secs.length)} />
    );

您正在传递<LectureItem />这是一个新元素,而不是您要推送的元素,因此我们将传递长度(该元素的实际新索引)。

下一步将您removeLectureHandler更改为此

removeLectureHandler = (indexToDelete) => {
    console.log(indexToDelete);
    const secs = this.state.sections;
    secs.splice(indexToDelete, 1);
    this.setState({ sections: secs });

};

您已经成功从“部分”和UI中删除了一个元素:-0