首页 > 解决方案 > 在 React 中使用 js 创建 html 块

问题描述

我创建了一个函数,该函数通常为数组中的每个数据创建 html 块,但它不起作用。有人能帮助我吗 。

这是功能:

makeGrid (){

    var data = test.map( x => [ x.name, x.price, ] );

    data.forEach(function(element) {
        var elem = () => ({
            type: 'div',
            props: {
                className: 'box',
                children: [{
                    type: 'i',
                    props: {
                        className: 'hvhv'
                    }
                }, {
                    type: 'h3',
                    props: {
                        children: element[0]
                    }
                }, {
                    type: 'p',
                    props: {
                        children: element[1]
                    }
                }]
                }
        });

        return elem;
    });

}

在这里我执行了这个功能:

render() {
    return (
        <div className = "Grid" >
        < section className = "boxes" >

        <h1> {this.makeGrid()} </h1>

        < /section> < /div > );
  }
}

export default Grid;

我希望这些块像:

    < div className = "box" >
    < i className = "fas fa-chart-pie fa-4x" > < /i>
    <h3 > Analytics < /h3 >
    <p > Lorem ipsum dolor sit amet, consectetur adipisicing elit.Quasi, expedita ? < /p > < /div >

标签: javascripthtmlreactjs

解决方案


你可以添加returnforEach

makeGrid (){

var data = test.map( x => [ x.name, x.price, ] );

return data.forEach(function(element) {
    var elem = () => ({
        type: 'div',
        props: {
            className: 'box',
            children: [{
                type: 'i',
                props: {
                    className: 'hvhv'
                }
            }, {
                type: 'h3',
                props: {
                    children: element[0]
                }
            }, {
                type: 'p',
                props: {
                    children: element[1]
                }
            }]
            }
    });

    return elem;
});

 }

推荐阅读