简体   繁体   中英

Appending React Components to Elements outside of JSX?

I have this React Component:

import React, { useEffect } from 'react'
import styles from './_PhotoCollage.module.scss'
import PhotoCard from '../PhotoCard'

const PhotoCollage = ({ author }) => {
  let i = 1
  useEffect(() => {
    author.posts.forEach(post => {
      document.getElementById(`collage-${i}`).appendChild(<PhotoCard/>)
      i++
      if (i > 4) i = 1
    })
  }, [])

  return (
    <div className={styles.photoCollage}>
      <div className={styles.col} id="collage-1"/>
      <div className={styles.col} id="collage-2"/>
      <div className={styles.col} id="collage-3"/>
      <div className={styles.col} id="collage-4"/>
    </div>
  )
}

export default PhotoCollage

appendChild() doesn't like this at all.

I could easily create four loops inside each <div className={styles.col} id="collage-X"/> but I'd like to find a way to do this with one loop as it looks cleaner and I imagine will be more optimal/faster.

Is there a way to append React Components to specific elements using the DOM?

With React you can do something like:

const PhotoCard = ({ id }) => <div>Photo-{id}</div>;

const PhotoCollage = () => {
  return (
    <div>
      {[...Array(5).keys()].map(key => (
        <div key={key} id={`collage-${key}`}>
          <PhotoCard id={key} />
        </div>
      ))}
    </div>
  );
};

编辑 zealous-framework-g9shx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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