繁体   English   中英

如何将动态创建的元素注入 React JSX 中的现有 div?

[英]How to inject a dinamically created element into an existing div in React JSX?

我有一个来自 json 数据文件的对象photos列表,我想将其组织成 3 个不同的<div>列,但我不知道如何实现,这是我损坏的未优化代码:

<div className="container">
    <div ref={leftColRef} className="left-col" />
    <div ref={centreColRef} className="centre-col" />
    <div ref={rightColRef} className="right-col" />
    {Object.keys(photos).forEach((n, i) => {
        const id = photos[n].id;
        const thumb = photos[n].thumbnailUrl;
        const title = photos[n].title;
        const element = (
            <Thumbnail id={id} title={title} thumb={thumb} />
        );
        if (i % 3 === 0) {
            leftColRef.current.append(element);
        } else if (i % 3 === 1) {
            centreColRef.current.append(element);
        } else {
            rightColRef.current.append(element);
        }
        // this line works, it idsplays the data but is commented as the data needs to go inside its respective columns
        // return <Thumbnail key={id} title={title} thumb={thumb} />;
    })}
</div>

这个想法是当i%3 = 0时将一些元素插入左列,而当i%3 = 1时将其他元素插入中心列,依此类推......

和我的代码和盒子的链接

任何帮助/建议将不胜感激。

最简单的可能是在渲染函数之外准备数据并一一渲染列。

您不应该像使用 JSX 在 jQuery 中那样操作 DOM

例子:

const Component = (props) => {
    const filterPhotos = (column) => {
        return props.photos.filter((photo,index)=> index%3==column);
    }

    return <>
        <MyColumn photos={filterPhotos(0)}/>
        <MyColumn photos={filterPhotos(1)}/>
        <MyColumn photos={filterPhotos(2)}/>
    </>;
}

首先,在 div 上使用 ref 来注入东西是错误的。 这与 react 的工作方式相反。

就像查理说的那样,我会在渲染之前将照片分成 3 个不同的数组。 然后,您将能够执行以下操作:

<div ref={leftColRef} className="left-col" /> { photosLeft.map(photo => <Thumbnail key={photo.id} {...photo} />) </div>

准备数据时,请尝试使用相同的对象属性和组件道具名称,以便轻松传播它( {...photo} )。

注意:另外,在 react 中渲染数组时,每个孩子都必须有一个唯一的 key props。 如果您的数据发生变化,它将有助于在 dom 的那部分进行渲染。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM