在listItem React内部动态插入组件

时间:2018-11-26 08:55:32

标签: javascript reactjs

如何使用React将子元素添加到父列表项元素中?

在列表元素上单击用户后,我需要插入元素,然后将其插入此元素内。


import React from 'react';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';


const ListOfSubcategories = (props) => {
    return (
        <List>
        {props.subcategories.map( category => {
            return (
                <ListItem key={category.id} button divider selected onClick={() => props.getCategories((category.id))}>
                    <ListItemText align="center">
                        {category.name}
                    </ListItemText>
         </ListItem>
            );
        })}
        </List>
    );
};

export default ListOfSubcategories;


import React, { Component } from 'react';
import Typography from '@material-ui/core/Typography';
import { postToServer, ERRORS } from '../../store/postToServer/postToServer';
import Button from '@material-ui/core/Button';
import ListOfCategories from '../../components/ListSubcategories/ListSubcategories';

class Categories extends Component {

state = {
    openSubcategories: false
};

categories = [];

getCategories = (idCategory) => {
    postToServer(URL.getCategories, { category_id: idCategory }, (res) => {
        if (parseInt(res.error) === ERRORS.NONE) {
            this.categories.push(res.data);
            this.setState({ openSubcategories: true });
        } else {
            this.props.showError(res.message);
        }
    });
};

componentDidMount() {
    postToServer(URL.getCategories, {}, (res) => {
        if (parseInt(res.error) === ERRORS.NONE) {
            this.categories = res.data;
            this.setState({ openSubcategories: true });
        } else {
            this.props.showError(res.message);
        }
    });
};

render() {
    return (
        <>
            <Typography>List of categories</Typography>
            <div>
                <ListOfCategories
                    subcategories={this.categories}
                    getCategories={this.getCategories}
                />
            </div>
        </>
    );
}
}

export default Categories;

我想在我的列表类别中添加子类别的列表,但是我不知道其内部级别。 我有一个数组根类别,然后用户单击,我们需要在单击元素内渲染根类别和子类别。

0 个答案:

没有答案